Check if a JCheckBoxMenuItem is selected in its item change listener : JCheckBoxMenuItem « Swing « Java Tutorial






import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;

public class Main extends JFrame {
  JCheckBoxMenuItem check = new JCheckBoxMenuItem("Check");

  public Main() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JMenuBar bar = new JMenuBar();
    JMenu menu = new JMenu("Checkable");
    bar.add(menu);
    menu.add(check);

    check.addItemListener(new ItemListener() {
      public void itemStateChanged(ItemEvent e) {
        System.out.println("Checked? " + check.isSelected());
      }
    });

    setJMenuBar(bar);
    getContentPane().add(new JLabel("A placeholder"));

    pack();
    setSize(300, 300);
    setVisible(true);
  }

  public static void main(String arg[]) {
    new Main();
  }
}








14.24.JCheckBoxMenuItem
14.24.1.Using JCheckBoxMenuItem: setMnemonicUsing JCheckBoxMenuItem: setMnemonic
14.24.2.Listening to JCheckBoxMenuItem Events with an ActionListenerListening to JCheckBoxMenuItem Events with an ActionListener
14.24.3.Listening to JCheckBoxMenuItem with an ItemListenerListening to JCheckBoxMenuItem with an ItemListener
14.24.4.Initialize JCheckBoxMenuItem with checked optionInitialize JCheckBoxMenuItem with checked option
14.24.5.Check if a JCheckBoxMenuItem is selected in its item change listener
14.24.6.Customizing JCheckBoxMenuItem Look and Feel