Listen for Action Events from a JComboBox in Java

Description

The following code shows how to listen for Action Events from a JComboBox.

Example


//ww w  . j  a v  a2s .  c o m
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] argv) throws Exception {
    JFrame frame = new JFrame("Selecting JComboBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    String[] items = { "item1", "item2" };
    JComboBox cb = new JComboBox(items);
    

    MyActionListener actionListener = new MyActionListener();
    cb.addActionListener(actionListener);
    
    
    frame.add(cb, BorderLayout.SOUTH);

    frame.setSize(400, 200);
    frame.setVisible(true);
    
    
  }
}

class MyActionListener implements ActionListener {
  Object oldItem;

  public void actionPerformed(ActionEvent evt) {
    JComboBox cb = (JComboBox) evt.getSource();
    Object newItem = cb.getSelectedItem();

    boolean same = newItem.equals(oldItem);
    oldItem = newItem;

    if ("comboBoxEdited".equals(evt.getActionCommand())) {
      System.out.println("comboBoxEdited");
      // User has typed in a string; only possible with an editable combobox
    } else if ("comboBoxChanged".equals(evt.getActionCommand())) {
      System.out.println("comboBoxChanged");
      // User has selected an item; it may be the same item
    }
  }
}

The code above generates the following result.

Listen for Action Events from a JComboBox in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer