Java Swing How to - Handle JComboBox Item Change event








Question

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

Answer

import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
/*from   w ww  .  ja  v  a2  s. c  o m*/
public class Main {

  public static void main(String[] args) {
    String[] items = { "item1", "item2", "item1" };
    JList<String> list = new JList<>(items);
    JTextField output = new JTextField(15);
    JPanel gui = new JPanel();
    gui.add(list);
    gui.add(output);
    list.addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent lse) {
        int index = list.getSelectedIndex();
        String outputText = "Index: " + index + "  Value: " + items[index];
        output.setText(outputText);
      }
    });
    JOptionPane.showMessageDialog(null, gui);
  }
}