Java AWT ItemListener handle item selection event on JCheckBox

Description

Java AWT ItemListener handle item selection event on JCheckBox


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 Main {
  public static void main(String args[]) {
    JFrame frame = new JFrame("CheckBox");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JCheckBox checkBox = new JCheckBox("CSS");

    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);
        }/* w  w w  .  ja va2  s  .co m*/
      }
    };
    checkBox.addItemListener(itemListener);
    frame.add(checkBox);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}



PreviousNext

Related