Java JCheckBox handle action event

Description

Java JCheckBox handle action event

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

      ActionListener actionListener = new ActionListener() {
         public void actionPerformed(ActionEvent actionEvent) {
            AbstractButton abstractButton = (AbstractButton) actionEvent.getSource();
            boolean selected = abstractButton.getModel().isSelected();
            System.out.println(selected);
         }/*from w w  w .  ja v a  2 s  . com*/
      };
      checkBox.addActionListener(actionListener);
      frame.add(checkBox);
      frame.setSize(300, 200);
      frame.setVisible(true);
   }
}



PreviousNext

Related