How to Write an Item Listener : ItemListener « Swing Event « Java Tutorial






How to Write an Item Listener
import java.awt.Color;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;

public class JCheckBoxItemListener {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Iconizing CheckBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JCheckBox aCheckBox4 = new JCheckBox("Stuffed Crust");

    ItemListener itemListener = new ItemListener() {
      public void itemStateChanged(ItemEvent itemEvent) {
        AbstractButton abstractButton = (AbstractButton)itemEvent.getSource();
        Color foreground = abstractButton.getForeground();
        Color background = abstractButton.getBackground();
        int state = itemEvent.getStateChange();
        if (state == ItemEvent.SELECTED) {
          abstractButton.setForeground(background);
          abstractButton.setBackground(foreground);
        }
      }
    };
    aCheckBox4.addItemListener(itemListener);
    frame.add(aCheckBox4);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}








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