Selecting a JComboBox item programmatically is pretty simple. Call either setSelectedIndex() or setSelectedItem() and that’s it. Problem is though, if you added an ItemListener to the JComboBox object, every time you do a select programmatically, the ItemStateChanged event method also gets affected.

Calling those two select methods from a JComboBox object is the most prone thing that developers do. However, if you do not want the ItemStateChanged method to be affected when you select an item programmatically, you can create a dummy variable inside the ItemStateChanged method so that it would not get affected. Sad to say, that is the alternative aside from adding and removing the ItemListener.

By default, Java’s JComboBox does not have the same feature as the HTML dropdown’s SELECT tag. You know the label and value in the OPTION tag. If you want to have the same feature for the JComboBox, you would have to ceate your own KeyValue class that contains the key (label) and the value. See the code below.

Make sure the toString() method returns the variable key so that it will be what will appear in the JComboBox’s list. To add it to the JComboBox, do it like this.

To get the selected item, do this.

Related Posts Plugin for WordPress, Blogger...