Java JCheckBox handle change event

Description

Java JCheckBox handle change event

import javax.swing.AbstractButton;
import javax.swing.ButtonModel;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

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");

    ChangeListener changeListener = new ChangeListener() {
      public void stateChanged(ChangeEvent changeEvent) {
        AbstractButton abstractButton =
          (AbstractButton)changeEvent.getSource();
        ButtonModel buttonModel = abstractButton.getModel();
        boolean armed = buttonModel.isArmed();
        boolean pressed = buttonModel.isPressed();
        boolean selected = buttonModel.isSelected();
        System.out.println("Changed: " + armed + "/" + pressed + "/" +
          selected);//from  ww  w . jav  a 2 s  .  co  m
      }
    };

    checkbox.addChangeListener(changeListener);
    frame.add(checkbox);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}



PreviousNext

Related