1. Technology

ItemListener Example Code Program


Java Code:

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()
             public void run()
                 new ItemListenerExample();         
    public ItemListenerExample()
        JFrame guiFrame = new JFrame();
        //make sure the program exits when the frame closes
        guiFrame.setTitle("Mouse Event Example");
        //This will center the JFrame in the middle of the screen
        //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(){
            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");
                    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(feedbackScroll, BorderLayout.CENTER);
  1. About.com
  2. Technology
  3. Java
  4. Create User Interfaces
  5. Handling Events
  6. ItemListener Example Code Program - Java

©2014 About.com. All rights reserved.