Java Swing How to - Create JCheckBox from Action object








Question

We would like to know how to create JCheckBox from Action object.

Answer

/*w  w  w.ja va  2  s  .c  om*/
import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBox;

public class Main {
  public static void main(String[] argv) throws Exception {
    Action action = new AbstractAction("CheckBox Label") {
      // called when the button is pressed
      public void actionPerformed(ActionEvent evt) {
        JCheckBox cb = (JCheckBox) evt.getSource();
        // Determine status
        boolean isSel = cb.isSelected();
        if (isSel) {
          // selected
        } else {
          // deselected
        }
      }
    };

    // Create the checkbox from the action
    JCheckBox checkBox = new JCheckBox(action);

  }
}