Java Swing How to - Trigger event from JComboBox AFTER selection








Question

We would like to know how to trigger event from JComboBox AFTER selection.

Answer

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
//from w  ww  . j  a  v a 2  s .  c o m
import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {
  public static void main(String[] args) {
    JComboBox<String> box = new JComboBox<>();
    box.addItem("One");
    box.addItem("Two");
    box.addItem("Three");

    box.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        if (e.getStateChange() == ItemEvent.SELECTED) {
          System.out.println(e.getItem());
        }
      }
    });
    JFrame frame = new JFrame();
    frame.getContentPane().add(box);
    frame.pack();
    frame.setVisible(true);
  }
}