The following example illustrates creating JCheckBoxMenuItem in Swing. This example covers all the constructors and important methods of the class.
import javax.swing.*;
import java.awt.*;
class JCheckBoxMenuItemExample extends JFrame
{
JMenuBar mb;
JMenu m;
JCheckBoxMenuItem m1,m2,m3,m4,m5,m6,m7;
ImageIcon i1;
public JCheckBoxMenuItemExample()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JCheckBoxMenuItem Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
mb=new JMenuBar();
m=new JMenu("Menu");
i1=new ImageIcon("imageicon.png");
m1=new JCheckBoxMenuItem();
m2=new JCheckBoxMenuItem(new javax.swing.text.DefaultEditorKit.BeepAction());
m3=new JCheckBoxMenuItem(i1);
m4=new JCheckBoxMenuItem("Item 4");
m5=new JCheckBoxMenuItem("Item 5",true);
m6=new JCheckBoxMenuItem("Item 5",i1);
m7=new JCheckBoxMenuItem("Item 6",i1,true);
// Set text
m1.setText("Item 1");
m1.setIcon(i1);
m1.setMnemonic('1');
m1.setFont(new Font("Tahoma",Font.PLAIN,11));
m1.setState(true);
// m1.setSelected(true);
// Set a shortcut
m2.setAccelerator(KeyStroke.getKeyStroke("ctrl 2"));
// disable m4
m4.setEnabled(false);
// Set tooltip text
m2.setToolTipText("This produces beep");
m.add(m1);
m.add(m2);
m.add(m3);
m.add(m4);
m.add(m5);
m.add(m6);
m.add(m7);
mb.add(m);
setJMenuBar(mb);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JCheckBoxMenuItemExample();
}
}