import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Menus extends JMenuBar implements ActionListener { public Menus() { //Create the menus and set a mnemonic for the edit menu. JMenu editMenu = new JMenu("Edit"); editMenu.setMnemonic( 'E' ); JMenu otherMenu = new JMenu("Other"); JMenu subMenu = new JMenu("SubMenu"); JMenu subMenu2 = new JMenu("SubMenu2"); // Assemble the edit menu with keyboard accelerators and mnemonics. JMenuItem item = new JMenuItem( "Cut", 'C' ); // Create and set the keyboard accelerator. item.setAccelerator(KeyStroke.getKeyStroke( "control X" ) ); item.addActionListener(this); //Add the item to the menu. editMenu.add(item); item = new JMenuItem( "Copy", 'O' ); // Create and set the keyboard accelerator. item.setAccelerator(KeyStroke.getKeyStroke( 'C', java.awt.Event.CTRL_MASK, false)); item.addActionListener(this); //Add the item to the menu. editMenu.add(item); item = new JMenuItem( "Paste", 'P' ); // Create and set the keyboard accelerator. item.setAccelerator(KeyStroke.getKeyStroke( 'V', java.awt.Event.CTRL_MASK, false)); item.addActionListener(this); //Add the item to the menu. editMenu.add(item); // Assemble the submenus of the Other Menu subMenu2.add(item = new JMenuItem("Extra 2")); item.addActionListener(this); subMenu.add(item = new JMenuItem("Extra 1")); item.addActionListener(this); subMenu.add(subMenu2); // Assemble the Other Menu itself otherMenu.add(subMenu); //A checkbox menu item. otherMenu.add(item = new JCheckBoxMenuItem("Check Me")); item.addActionListener(this); // Place separator ( a line ) in the menu. otherMenu.addSeparator(); //Make a group of two radiobutton items. ButtonGroup buttonGroup = new ButtonGroup(); otherMenu.add(item = new JRadioButtonMenuItem("Radio 1")); item.addActionListener(this); buttonGroup.add(item); otherMenu.add(item = new JRadioButtonMenuItem("Radio 2")); item.addActionListener(this); buttonGroup.add(item); otherMenu.addSeparator(); //This menu item has an icon. otherMenu.add(item = new JMenuItem("Potted Plant", new ImageIcon("plant.gif"))); item.addActionListener(this); // Finally, add all the menus to the menubar add(editMenu); add(otherMenu); } public void actionPerformed(ActionEvent event) { System.out.println("Menu item [" + event.getActionCommand() + "] was pressed."); } public static void main(String s[]) { JFrame frame = new JFrame("Simple Menu Example"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); //Place the menubar in the frames layeredPane. frame.setJMenuBar(new Menus()); frame.setSize( 200, 200 ); frame.setVisible(true); } }