This example Java program shows how to handle item events triggered by selecting and deselecting items from a JComboBox by using an ItemListener event listener.
When run this application displays a GUI made up of a JFrame containing a JComboBox and a JTextArea. As items are selected in the JComboBox the JTextArea logs the item events triggered.
The article that goes with this Java code listing is How to Handle Item Events.
//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import java.awt.EventQueue;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JComboBox;
import javax.swing.JScrollPane;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
public class ItemListenerExample {
JTextArea feedback;
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new ItemListenerExample();
}
});
}
public ItemListenerExample()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Mouse Event Example");
guiFrame.setSize(700,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//Options for the combo box dialog
String[] choices = {"Monday", "Tuesday"
,"Wednesday", "Thursday", "Friday"};
JComboBox weekDays = new JComboBox(choices);
//Attach an ItemListener to weekDays by using
//an anonymous inner class
weekDays.addItemListener(new ItemListener(){
@Override
public void itemStateChanged(ItemEvent e)
{
//getItem returns an object so it gets cast
//as a String to retrieve the item value
String item = (String)e.getItem();
if (e.getStateChange() == ItemEvent.SELECTED)
{
feedback.append(item + " was selected\n");
}
else
{
feedback.append(item + " was deselected\n");
}
}
});
feedback = new JTextArea();
//Put the textArea into a JScrollPane to be able to
//scroll through all the item events triggered
JScrollPane feedbackScroll = new JScrollPane(feedback);
guiFrame.add(weekDays,BorderLayout.NORTH);
guiFrame.add(feedbackScroll, BorderLayout.CENTER);
guiFrame.setVisible(true);
}
}

