首页javajcomboboxJava Swing - 如何处理JComboBox的操作事件

Java Swing - 如何处理JComboBox的操作事件

我们想知道如何处理JComboBox的操作事件。
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

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);
  }
}