Java Swing How to - Get selected item from JComboBox in Action event handler








Question

We would like to know how to get selected item from JComboBox in Action event handler.

Answer

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*from w  ww  .  j av a2s.co m*/
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JPanel {
  public Main() {
    String[] comboTypes = { "Numbers", "Alphabets", "Symbols" };
    JComboBox<String> comboTypesList = new JComboBox<>(comboTypes);
    comboTypesList.setSelectedIndex(2);
    comboTypesList.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        JComboBox jcmbType = (JComboBox) e.getSource();
        String cmbType = (String) jcmbType.getSelectedItem();
        System.out.println(cmbType);
      }
    });
    setLayout(new BorderLayout());
    add(comboTypesList, BorderLayout.NORTH);
  }
  public static void main(String s[]) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new Main());
    frame.pack();
    frame.setVisible(true);
  }
}