Java Tutorial/Swing/JMenu

Материал из Java эксперт
Версия от 18:33, 31 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Adding a Menu to a Window

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; public class AddMenuBarToFrame extends JFrame {

 private JMenuBar menuBar = new JMenuBar(); // Window menu bar
 public AddMenuBarToFrame(String title) {
   setTitle(title);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setJMenuBar(menuBar); // Add the menu bar to the window
   JMenu fileMenu = new JMenu("File"); // Create File menu
   JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
   menuBar.add(fileMenu); // Add the file menu
   menuBar.add(elementMenu); // Add the element menu
 }
 public static void main(String[] args) {
   AddMenuBarToFrame window = new AddMenuBarToFrame("Sketcher"); 
   window.setBounds(30, 30, 300, 300);
   window.setVisible(true);
 }

}</source>





Adding Menu Shortcuts

   <source lang="java">

import static java.awt.event.InputEvent.CTRL_DOWN_MASK; import javax.swing.ButtonGroup; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; public class FramewithMenuShortcut extends JFrame {

 private JMenuBar menuBar = new JMenuBar(); // Window menu bar
 private JMenuItem newItem, openItem, closeItem, saveItem, saveAsItem, printItem;
 private JRadioButtonMenuItem lineItem, rectangleItem, circleItem;
 private JCheckBoxMenuItem redItem, yellowItem;
 public FramewithMenuShortcut(String title) {
   JMenu fileMenu = new JMenu("File"); // Create File menu
   JMenu elementMenu = new JMenu("Elements"); // Create Elements menu
   fileMenu.setMnemonic("F"); // Create shortcut
   elementMenu.setMnemonic("E"); // Create shortcut
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setJMenuBar(menuBar);
   newItem = fileMenu.add("New");
   openItem = fileMenu.add("Open");
   closeItem = fileMenu.add("Close");
   fileMenu.addSeparator();
   saveItem = fileMenu.add("Save");
   saveAsItem = fileMenu.add("Save As...");
   fileMenu.addSeparator();
   printItem = fileMenu.add("Print");
   elementMenu.add(lineItem = new JRadioButtonMenuItem("Line", true));
   elementMenu.add(rectangleItem = new JRadioButtonMenuItem("Rectangle", false));
   elementMenu.add(circleItem = new JRadioButtonMenuItem("Circle", false));
   ButtonGroup types = new ButtonGroup();
   types.add(lineItem);
   types.add(rectangleItem);
   types.add(circleItem);
   elementMenu.addSeparator();
   elementMenu.add(redItem = new JCheckBoxMenuItem("Red", false));
   elementMenu.add(yellowItem = new JCheckBoxMenuItem("Yellow", false));
   menuBar.add(fileMenu);
   menuBar.add(elementMenu);
   newItem.setAccelerator(KeyStroke.getKeyStroke("N", CTRL_DOWN_MASK));
   openItem.setAccelerator(KeyStroke.getKeyStroke("O", CTRL_DOWN_MASK));
   saveItem.setAccelerator(KeyStroke.getKeyStroke("S", CTRL_DOWN_MASK));
   printItem.setAccelerator(KeyStroke.getKeyStroke("P", CTRL_DOWN_MASK));
   lineItem.setAccelerator(KeyStroke.getKeyStroke("L", CTRL_DOWN_MASK));
   rectangleItem.setAccelerator(KeyStroke.getKeyStroke("E", CTRL_DOWN_MASK));
   circleItem.setAccelerator(KeyStroke.getKeyStroke("I", CTRL_DOWN_MASK));
   elementMenu.addSeparator();
   redItem.setAccelerator(KeyStroke.getKeyStroke("R", CTRL_DOWN_MASK));
   yellowItem.setAccelerator(KeyStroke.getKeyStroke("Y", CTRL_DOWN_MASK));
   menuBar.add(fileMenu);
   menuBar.add(elementMenu);
 }
 public static void main(String[] a) {
   FramewithMenuShortcut window = new FramewithMenuShortcut("");
   window.setBounds(30, 30, 300, 300);
   window.setVisible(true);
 }

}</source>





Add Separator to JMenu

   <source lang="java">

import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JSeparator; public class MenuSeparator extends JFrame {

 public MenuSeparator() {
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new JMenuBar();
   JMenu menu = new JMenu("File");
   bar.add(menu);
   menu.add(new JMenuItem("Close"));
   menu.add(new JSeparator()); // SEPARATOR
   menu.add(new JMenuItem("Exit"));
   setJMenuBar(bar);
   getContentPane().add(new JLabel("A placeholder"));
   pack();
   setSize(300, 300);
   setVisible(true);
 }
 public static void main(String arg[]) {
   new MenuSeparator();
 }

}</source>





Customizing JMenu Look and Feel

Property StringObject TypeMenu.acceleratorDelimiterStringMenu.acceleratorFontFontMenu.acceleratorForegroundColorMenu.acceleratorSelectionForegroundColorMenu.ActionMapActionMapMenu.arrowIconIconMenu.backgroundColorMenu.borderBorderMenu.borderPaintedBooleanMenu.checkIconIconMenu.delayIntegerMenu.disabledForegroundColorMenu.fontFontMenu.foregroundColorMenu.marginInsetsMenu.menuPopupOffsetXIntegerMenu.menuPopupOffsetYIntegerMenu.opaqueBooleanMenu.selectionBackgroundColorMenu.selectionForegroundColorMenu.shortcutKeysint[ ]Menu.submenuPopupOffsetXIntegerMenu.submenuPopupOffsetYIntegerMenu.textIconGapIntegerMenu.useMenuBarBackgroundForTopLevelBooleanmenuPressedItemBColormenuPressedItemFColormenuTextColorMenuUIString


Layout menu yourself

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPopupMenu; /**

* @author ges
* @author kwalrath
*/

/* MenuLayoutDemo.java requires no other files. */ public class MenuLayoutDemo {

 public JMenuBar createMenuBar() {
   JMenuBar menuBar = new JMenuBar();
   menuBar.setLayout(new BoxLayout(menuBar, BoxLayout.PAGE_AXIS));
   menuBar.add(createMenu("Menu 1"));
   menuBar.add(createMenu("Menu 2"));
   menuBar.add(createMenu("Menu 3"));
   menuBar.setBorder(BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK));
   return menuBar;
 }
 // used by createMenuBar
 public JMenu createMenu(String title) {
   JMenu m = new HorizontalMenu(title);
   m.add("Menu item #1 in " + title);
   m.add("Menu item #2 in " + title);
   m.add("Menu item #3 in " + title);
   JMenu submenu = new HorizontalMenu("Submenu");
   submenu.add("Submenu item #1");
   submenu.add("Submenu item #2");
   m.add(submenu);
   return m;
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   // Create and set up the window.
   JFrame frame = new JFrame("MenuLayoutDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Create and set up the content pane.
   MenuLayoutDemo demo = new MenuLayoutDemo();
   Container contentPane = frame.getContentPane();
   contentPane.setBackground(Color.WHITE); // contrasting bg
   contentPane.add(demo.createMenuBar(), BorderLayout.LINE_START);
   // Display the window.
   frame.setSize(300, 150);
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }
 class HorizontalMenu extends JMenu {
   HorizontalMenu(String label) {
     super(label);
     JPopupMenu pm = getPopupMenu();
     pm.setLayout(new BoxLayout(pm, BoxLayout.LINE_AXIS));
   }
   public Dimension getMinimumSize() {
     return getPreferredSize();
   }
   public Dimension getMaximumSize() {
     return getPreferredSize();
   }
   public void setPopupMenuVisible(boolean b) {
     boolean isVisible = isPopupMenuVisible();
     if (b != isVisible) {
       if ((b == true) && isShowing()) {
         // Set location of popupMenu (pulldown or pullright).
         // Perhaps this should be dictated by L&F.
         int x = 0;
         int y = 0;
         Container parent = getParent();
         if (parent instanceof JPopupMenu) {
           x = 0;
           y = getHeight();
         } else {
           x = getWidth();
           y = 0;
         }
         getPopupMenu().show(this, x, y);
       } else {
         getPopupMenu().setVisible(false);
       }
     }
   }
 }

}</source>





Listening to JMenu Events with a ChangeListener: register a ChangeListener with a JMenu

   <source lang="java">

import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class ContructMenuWithAction {

 public static void main(final String args[]) {
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar menuBar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic(KeyEvent.VK_F);
   menuBar.add(fileMenu);
   fileMenu.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent e) {
       System.out.println("File Menu Changed");
     }
   });
   // File->New, N - Mnemonic
   JMenuItem newMenuItem = new JMenuItem("New");
   fileMenu.add(newMenuItem);
   newMenuItem.addChangeListener(new ChangeListener() {
     public void stateChanged(ChangeEvent e) {
       System.out.println("new menu item changed");
     }
   });
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}</source>





Set Mnemonic key

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; class MenuActionListener implements ActionListener {

 public void actionPerformed(ActionEvent actionEvent) {
   System.out.println("Selected: " + actionEvent.getActionCommand());
 }

} public class MenuAction {

 public static void main(final String args[]) {
   ActionListener menuListener = new MenuActionListener();
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar menuBar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic(KeyEvent.VK_F);
   menuBar.add(fileMenu);
   // File->New, N - Mnemonic
   JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
   newMenuItem.addActionListener(menuListener);
   fileMenu.add(newMenuItem);
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}</source>





Submenu

   <source lang="java">

import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class Submenu {

 public static void main(final String args[]) {
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar menuBar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic(KeyEvent.VK_F);
   menuBar.add(fileMenu);
   // File->New, N - Mnemonic
   JMenuItem newMenuItem = new JMenuItem("New", KeyEvent.VK_N);
   fileMenu.add(newMenuItem);
   // Edit->Options Submenu, O - Mnemonic, at.gif - Icon Image File
   JMenu findOptionsMenu = new JMenu("Options");
   Icon atIcon = new ImageIcon("at.gif");
   findOptionsMenu.setIcon(atIcon);
   findOptionsMenu.setMnemonic(KeyEvent.VK_O);
   fileMenu.add(findOptionsMenu);
   // ButtonGroup for radio buttons
   ButtonGroup directionGroup = new ButtonGroup();
   // Edit->Options->Forward, F - Mnemonic, in group
   JRadioButtonMenuItem forwardMenuItem = new JRadioButtonMenuItem("Forward", true);
   forwardMenuItem.setMnemonic(KeyEvent.VK_F);
   findOptionsMenu.add(forwardMenuItem);
   directionGroup.add(forwardMenuItem);
   // Edit->Options->Backward, B - Mnemonic, in group
   JRadioButtonMenuItem backwardMenuItem = new JRadioButtonMenuItem("Backward");
   backwardMenuItem.setMnemonic(KeyEvent.VK_B);
   findOptionsMenu.add(backwardMenuItem);
   directionGroup.add(backwardMenuItem);
   
   
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}</source>





The JMenu component is the basic menu item container that is placed on a JMenuBar

  1. In various places within the different menus, menu separators divide the options into logical sets.
  2. Each of the menu options has a mnemonic associated with it to help with keyboard navigation and selection.
  3. The mnemonic allows users to make menu selections via the keyboard, for instance, by pressing Alt-F on a Windows platform to open the File menu.
  4. A keystroke associated with several options acts as a keyboard accelerator. Unlike the mnemonic, the accelerator can directly activate a menu option, even when the menu option isn"t visible.
  5. The Options submenu has an icon associated with it.



   <source lang="java">

JMenu fileMenu = new JMenu("File"); JMenuItem newMenuItem = new JMenuItem("New"); fileMenu.add(newMenuItem); JMenuItem openMenuItem = new JMenuItem("Open"); fileMenu.add(openMenuItem); JMenuItem closeMenuItem = new JMenuItem("Close"); fileMenu.add(closeMenuItem); fileMenu.addSeparator(); JMenuItem saveMenuItem = new JMenuItem("Save"); fileMenu.add(saveMenuItem); fileMenu.addSeparator(); JMenuItem exitMenuItem = new JMenuItem("Exit"); fileMenu.add(exitMenuItem);</source>





Using Action Objects with Menus

Creating a specific implementation of AbstractAction and adds it to a JMenu multiple times



   <source lang="java">

import java.awt.ruponent; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; class ShowAction extends AbstractAction {

 Component parentComponent;
 public ShowAction(Component parentComponent) {
   super("About");
   putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_A));
   this.parentComponent = parentComponent;
 }
 public void actionPerformed(ActionEvent actionEvent) {
   Runnable runnable = new Runnable() {
     public void run() {
       JOptionPane.showMessageDialog(parentComponent, "About Swing", "About Box V2.0",
           JOptionPane.INFORMATION_MESSAGE);
     }
   };
   EventQueue.invokeLater(runnable);
 }

} public class ContructMenuWithAction {

 public static void main(final String args[]) {
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar menuBar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic(KeyEvent.VK_F);
   menuBar.add(fileMenu);
   // File->New, N - Mnemonic
   JMenuItem newMenuItem = new JMenuItem(new ShowAction(frame));
   fileMenu.add(newMenuItem);
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}</source>





Using MenuListener to listen to: menu canceled, selected and deselected events

With a registered MenuListener, you"re notified when a JMenu is selected before the pop-up menu is opened with the menu"s choices.



   <source lang="java">

public interface MenuListener extends EventListener {

 public void menuCanceled(MenuEvent e);
 public void menuDeselected(MenuEvent e);
 public void menuSelected(MenuEvent e);

}</source>





what menus look like

   <source lang="java">

/*

* Copyright (c) 1995 - 2008 Sun Microsystems, Inc.  All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
*   - Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*
*   - Redistributions in binary form must reproduce the above copyright
*     notice, this list of conditions and the following disclaimer in the
*     documentation and/or other materials provided with the distribution.
*
*   - Neither the name of Sun Microsystems nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; /* MenuLookDemo.java requires images/middle.gif. */ /*

* This class exists solely to show you what menus look like. It has no
* menu-related event handling.
*/

public class MenuLookDemo {

 JTextArea output;
 JScrollPane scrollPane;
 public JMenuBar createMenuBar() {
   JMenuBar menuBar;
   JMenu menu, submenu;
   JMenuItem menuItem;
   JRadioButtonMenuItem rbMenuItem;
   JCheckBoxMenuItem cbMenuItem;
   // Create the menu bar.
   menuBar = new JMenuBar();
   // Build the first menu.
   menu = new JMenu("A Menu");
   menu.setMnemonic(KeyEvent.VK_A);
   menu.getAccessibleContext().setAccessibleDescription(
       "The only menu in this program that has menu items");
   menuBar.add(menu);
   // a group of JMenuItems
   menuItem = new JMenuItem("A text-only menu item", KeyEvent.VK_T);
   // menuItem.setMnemonic(KeyEvent.VK_T); //used constructor instead
   menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_1,
       ActionEvent.ALT_MASK));
   menuItem.getAccessibleContext().setAccessibleDescription(
       "This doesn"t really do anything");
   menu.add(menuItem);
   ImageIcon icon = createImageIcon("images/middle.gif");
   menuItem = new JMenuItem("Both text and icon", icon);
   menuItem.setMnemonic(KeyEvent.VK_B);
   menu.add(menuItem);
   menuItem = new JMenuItem(icon);
   menuItem.setMnemonic(KeyEvent.VK_D);
   menu.add(menuItem);
   // a group of radio button menu items
   menu.addSeparator();
   ButtonGroup group = new ButtonGroup();
   rbMenuItem = new JRadioButtonMenuItem("A radio button menu item");
   rbMenuItem.setSelected(true);
   rbMenuItem.setMnemonic(KeyEvent.VK_R);
   group.add(rbMenuItem);
   menu.add(rbMenuItem);
   rbMenuItem = new JRadioButtonMenuItem("Another one");
   rbMenuItem.setMnemonic(KeyEvent.VK_O);
   group.add(rbMenuItem);
   menu.add(rbMenuItem);
   // a group of check box menu items
   menu.addSeparator();
   cbMenuItem = new JCheckBoxMenuItem("A check box menu item");
   cbMenuItem.setMnemonic(KeyEvent.VK_C);
   menu.add(cbMenuItem);
   cbMenuItem = new JCheckBoxMenuItem("Another one");
   cbMenuItem.setMnemonic(KeyEvent.VK_H);
   menu.add(cbMenuItem);
   // a submenu
   menu.addSeparator();
   submenu = new JMenu("A submenu");
   submenu.setMnemonic(KeyEvent.VK_S);
   menuItem = new JMenuItem("An item in the submenu");
   menuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_2,
       ActionEvent.ALT_MASK));
   submenu.add(menuItem);
   menuItem = new JMenuItem("Another item");
   submenu.add(menuItem);
   menu.add(submenu);
   // Build second menu in the menu bar.
   menu = new JMenu("Another Menu");
   menu.setMnemonic(KeyEvent.VK_N);
   menu.getAccessibleContext().setAccessibleDescription(
       "This menu does nothing");
   menuBar.add(menu);
   return menuBar;
 }
 public Container createContentPane() {
   // Create the content-pane-to-be.
   JPanel contentPane = new JPanel(new BorderLayout());
   contentPane.setOpaque(true);
   // Create a scrolled text area.
   output = new JTextArea(5, 30);
   output.setEditable(false);
   scrollPane = new JScrollPane(output);
   // Add the text area to the content pane.
   contentPane.add(scrollPane, BorderLayout.CENTER);
   return contentPane;
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path) {
   java.net.URL imgURL = MenuLookDemo.class.getResource(path);
   if (imgURL != null) {
     return new ImageIcon(imgURL);
   } else {
     System.err.println("Couldn"t find file: " + path);
     return null;
   }
 }
 /**
  * Create the GUI and show it. For thread safety, this method should be
  * invoked from the event-dispatching thread.
  */
 private static void createAndShowGUI() {
   // Create and set up the window.
   JFrame frame = new JFrame("MenuLookDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   // Create and set up the content pane.
   MenuLookDemo demo = new MenuLookDemo();
   frame.setJMenuBar(demo.createMenuBar());
   frame.setContentPane(demo.createContentPane());
   // Display the window.
   frame.setSize(450, 260);
   frame.setVisible(true);
 }
 public static void main(String[] args) {
   // Schedule a job for the event-dispatching thread:
   // creating and showing this application"s GUI.
   javax.swing.SwingUtilities.invokeLater(new Runnable() {
     public void run() {
       createAndShowGUI();
     }
   });
 }

}</source>