The following example illustrates JMenuItem in swing covering all constructors and core methods of the JMenuItem class.
import javax.swing.*;
import java.awt.*;
class JMenuItemExample extends JFrame
{
JMenuBar mb;
JMenu m;
JMenuItem m1,m2,m3,m4,m5,m6;
ImageIcon i1;
public JMenuItemExample()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("JMenuItem Example");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new FlowLayout());
mb=new JMenuBar();
m=new JMenu("Menu");
i1=new ImageIcon("imageicon.png");
m1=new JMenuItem();
m2=new JMenuItem(new javax.swing.text.DefaultEditorKit.BeepAction());
m3=new JMenuItem(i1);
m4=new JMenuItem("Item 4");
m5=new JMenuItem("Item 5",i1);
m6=new JMenuItem("Item 6",'6');
// Set text
m1.setText("Item 1");
m1.setIcon(i1);
m1.setMnemonic('1');
// 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);
mb.add(m);
setJMenuBar(mb);
setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
new JMenuItemExample();
}
}