Java Swing How to - Handle action event for JComboBox








Question

We would like to know how to handle action event for JComboBox.

Answer

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
//  w w  w  .ja  v a 2 s.com
public class Main extends JPanel {

  public Main() {
    JComboBox<String> cb = new JComboBox<>(
        new String[] { "a", "m", "b", "c", "v" });
    cb.setSelectedIndex(-1);

    JButton button = new JButton("Print Selection");
    button.addActionListener(e-> {
        if (cb.getSelectedIndex() != -1)
          System.out.println(cb.getSelectedItem());
        else
          System.out.println("Not selected");
    });

    add(cb);
    add(button);
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(new Main());
    f.pack();
    f.setSize(400, 300);
    f.setVisible(true);
  }
}