Java Swing How to - Handle Item event for JComboBox








Question

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

Answer

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
//from  w  w w .  ja  v  a  2 s .c o  m
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main implements ItemListener {
  JComboBox c;
  Main() {
    JFrame f1 = new JFrame("Selection");
    Container f = new Container();
    f.setLayout(new FlowLayout());

    String s[] = { "Red", "Green", "Yellow", "Black" };
    c = new JComboBox(s);
    JPanel p = new JPanel();

    c.addItemListener(this);

    f1.add(p);
    p.add(c);
    f1.setSize(500, 500);
    f1.setVisible(true);
  }

  public void itemStateChanged(ItemEvent ie) {
    String str = (String) c.getSelectedItem();
    System.out.println(str);
  }

  public static void main(String[] args) {
    new Main();
  }
}