ComboBox with ItemListener : ItemListener « Swing Event « Java Tutorial






ComboBox with ItemListener
import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

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

public class ComboBoxWithItemChangedListener extends JFrame {
  public static void main(String[] args) {
    ComboBoxWithItemChangedListener that = new ComboBoxWithItemChangedListener();
    that.setVisible(true);
  }

  public ComboBoxWithItemChangedListener() {
    setSize(450, 350);

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    getContentPane().add(new ComboPanel(), BorderLayout.SOUTH);
  }
}

class ComboPanel extends JPanel {
  final static String[] treasure = { "Gold", "Silver", "Diamonds", "Rubies", "Emeralds",
      "Sapphires", "Chocolate" };

  public ComboPanel() {
    final JComboBox combo = new JComboBox(treasure);
    combo.setMaximumRowCount(5);
    combo.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        System.out.println("Combo: " + combo.getSelectedItem());
      }
    });
    combo.setSelectedIndex(4);
    add(combo);
  }
}








15.20.ItemListener
15.20.1.How to Write an Item ListenerHow to Write an Item Listener
15.20.2.Toggle button with ItemListenerToggle button with ItemListener
15.20.3.ComboBox with ItemListenerComboBox with ItemListener
15.20.4.Firing Item Events
15.20.5.ItemListener for JRadioButton