1

Hey,

I'm trying to work to display a number of jtextfield according to one of the given values in a combobox.

So, I will have a drop down menu with let's say 1 to 4. If the user selects 3, 3 textfields will be displayed.

I've created the jcombobox with a selection of numbers. But I'm sure how to implement this. If I'm not mistaken I need to use

ItemEvent.SELECTED

Any help would be greatly appreciated.

3
Contributors
4
Replies
5
Views
5 Years
Discussion Span
Last Post by whateverme
1

JComboBox has a few methods that can help you in such cases. since you only want to have one item selected, you should use the

getSelectedItem()

method. if you want more information about what it does/returns, look at the JComboBox api

0

First you need to create a reference to the JTextField object that will be available to the JComboBox's itemListener object.

Add an ItemListener to the JComboBox to handle itemStateChanged events. in your handler get the selected item from the ItemEvent and pass it to the setText method of the JTextField Object.

Make sense?

Edited by ejosiah: n/a

1
// Add this class as a listener to the JComboBox object
public class ItemEventHandler implements ItemListener {
	/** 
           reference to textField we want to set
           jcombo's selected value **/
	private JTextField textField;
	
	public ItemEventHandler(JTextField tField){
		textField = tField;
	}

	public void itemStateChanged(ItemEvent event) {
		textField.setText(event.getItem().toString());	
	}

}

Edited by ejosiah: n/a

0

I've added this to my class :

public void itemStateChanged(ItemEvent event) {

        /*aOption is the combobox I declared 
        aOptionComboBox.setModel(new DefaultComboBoxModel(new String[]{"1","2","3"})); */

        String num = (String)aOptionComboBox.getSelectedItem(); 
        int num1 = Integer.parseInt(num);
        JTextField[] textfields = new JTextField[num1];

        for (int i = 0; i < num1; i++) 
        {
            textfields[i] = new JTextField("Field");
            getContentPane().add(textfields[i]);
            textfields[i].setBounds(200, 90, 100, 25);

        }
	}

am I on a right track?

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.