Java JComboBox - creating, adding a model, listening to item changes (user selections)

The following source code snippet shows how to create a JComboBox, set a simple DefaultComboBoxModel on it, and most importantly, add an ItemListener to it so your code can react to users changing the selection in the combobox.

The source code is written in Scala, but as you can see, it converts easily to Java:

// create a jcombobox
val languagesComboBox = new JComboBox

// give it a simple model
val languagesModel = new DefaultComboBoxModel(Array("Java", "JSON", "PHP", "Play", "Python"))
languagesComboBox.setModel(languagesModel)

This next source code example how to create a listener for the JComboBox, in this case an ItemListener:

// handle the case where the user changes the item selection in the jcombobox
val itemListener = new ItemListener {
    def itemStateChanged(itemEvent: ItemEvent) {
        val state = itemEvent.getStateChange
        if (state == ItemEvent.SELECTED) {
            val item = itemEvent.getItem.toString  // "Java", "JSON", etc.
            // now you can do something with the `item`, which is a String
        }
    }
}

As the comment shows, all you have to do in the itemStateChanged method is handle the item, which is the String that’s currently showing in the JComboBox.

Note that you do need to check that the state is equal to ItemEvent.SELECTED; each time a JComboBox selection is changed, two events are fired, one for the item that is de-selected, and one for the new item that is selected, and you generally just want one of those, i.e., the selected event, as shown.