Java Swing Tutorial - Java JComboBox .addActionListener (ActionListener l)


JComboBox.addActionListener(ActionListener l) has the following syntax.

public void addActionListener(ActionListener l)


In the following code shows how to use JComboBox.addActionListener(ActionListener l) method.

//from w w  w.ja  v a 2s. c om
import java.awt.BorderLayout;
import java.awt.ItemSelectable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JComboBox;
import javax.swing.JFrame;

public class Main {

  public static void main(final String args[]) {
    final String labels[] = { "A", "B", "C", "D", "E" };
    JFrame frame = new JFrame("Selecting JComboBox");

    JComboBox comboBox = new JComboBox(labels);
    frame.add(comboBox, BorderLayout.SOUTH);

    ActionListener actionListener = new ActionListener() {
      public void actionPerformed(ActionEvent actionEvent) {
        System.out.println("Command: " + actionEvent.getActionCommand());
        ItemSelectable is = (ItemSelectable)actionEvent.getSource();
        System.out.println(", Selected: " + selectedString(is));
    frame.setSize(400, 200);

  static private String selectedString(ItemSelectable is) {
    Object selected[] = is.getSelectedObjects();
    return ((selected.length == 0) ? "null" : (String)selected[0]);