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.

Recommended Answers

All 4 Replies

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

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?

// 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());	
	}

}

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.