Java/Swing JFC/Menu

Материал из Java эксперт
Перейти к: навигация, поиск

Содержание

Action Menu

   <source lang="java">
 

import java.awt.ruponent; import java.awt.Event; 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; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; public class ActionMenuSample {

 public static 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 Life", "About Box V1.0",
             JOptionPane.INFORMATION_MESSAGE);
       }
     };
     SwingUtilities.invokeLater(runnable);
   }
 }
 public static void main(String args[]) {
   JFrame frame = new JFrame("Action Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   Action showAction = new ShowAction(frame);
   JMenuBar menuBar = new JMenuBar();
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic("f");
   JMenuItem newMenuItem = new JMenuItem("New", "N");
   fileMenu.add(newMenuItem);
   JMenuItem openMenuItem = new JMenuItem("Open", "O");
   fileMenu.add(openMenuItem);
   JMenuItem closeMenuItem = new JMenuItem("Close", "C");
   fileMenu.add(closeMenuItem);
   fileMenu.addSeparator();
   JMenuItem saveMenuItem = new JMenuItem("Save", "S");
   fileMenu.add(saveMenuItem);
   fileMenu.add(showAction);
   fileMenu.addSeparator();
   JMenuItem exitMenuItem = new JMenuItem("Exit", "X");
   fileMenu.add(exitMenuItem);
   menuBar.add(fileMenu);
   JMenu editMenu = new JMenu("Edit");
   JMenuItem cutMenuItem = new JMenuItem("Cut", "T");
   KeyStroke ctrlXKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_X,
       Event.CTRL_MASK);
   cutMenuItem.setAccelerator(ctrlXKeyStroke);
   editMenu.add(cutMenuItem);
   JMenuItem copyMenuItem = new JMenuItem("Copy", "C");
   KeyStroke ctrlCKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_C,
       Event.CTRL_MASK);
   copyMenuItem.setAccelerator(ctrlCKeyStroke);
   editMenu.add(copyMenuItem);
   JMenuItem pasteMenuItem = new JMenuItem("Paste", "P");
   KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_V,
       Event.CTRL_MASK);
   pasteMenuItem.setAccelerator(ctrlVKeyStroke);
   pasteMenuItem.setEnabled(false);
   editMenu.add(pasteMenuItem);
   editMenu.addSeparator();
   JMenuItem findMenuItem = new JMenuItem("Find", "F");
   KeyStroke f3KeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0);
   findMenuItem.setAccelerator(f3KeyStroke);
   editMenu.add(findMenuItem);
   editMenu.setMnemonic("e");
   editMenu.add(showAction);
   menuBar.add(editMenu);
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Actions MenuBar

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.ruponent; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemListener; import java.util.Enumeration; import java.util.Vector; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.JTextPane; import javax.swing.border.Border; import javax.swing.event.ChangeListener; import javax.swing.text.JTextComponent; public class ActionsMenuBar {

 public static void main(String args[]) {
   final JFrame frame = new JFrame("TextAction Usage");
   Container contentPane = frame.getContentPane();
   final JScrollPane scrollPane = new JScrollPane();
   contentPane.add(scrollPane, BorderLayout.CENTER);
   final JMenuBar menuBar = new JMenuBar();
   frame.setJMenuBar(menuBar);
   ActionListener actionListener = new ActionListener() {
     JTextComponent component;
     public void actionPerformed(ActionEvent actionEvent) {
       // Determine which component selected
       String command = actionEvent.getActionCommand();
       if (command.equals("JTextField")) {
         component = new JTextField();
       } else if (command.equals("JPasswordField")) {
         component = new JPasswordField();
       } else if (command.equals("JTextArea")) {
         component = new JTextArea();
       } else if (command.equals("JTextPane")) {
         component = new JTextPane();
       } else {
         component = new JEditorPane();
       }
       scrollPane.setViewportView(component);
       // Process action list
       Action actions[] = component.getActions();
       menuBar.removeAll();
       menuBar.revalidate();
       JMenu menu = null;
       for (int i = 0, n = actions.length; i < n; i++) {
         if ((i % 10) == 0) {
           menu = new JMenu("From " + i);
           menuBar.add(menu);
         }
         menu.add(actions[i]);
       }
       menuBar.revalidate();
     }
   };
   String components[] = { "JTextField", "JPasswordField", "JTextArea",
       "JTextPane", "JEditorPane" };
   final Container componentsContainer = RadioButtonUtils
       .createRadioButtonGrouping(components, "Pick to List Actions",
           actionListener);
   contentPane.add(componentsContainer, BorderLayout.WEST);
   frame.setSize(400, 300);
   frame.setVisible(true);
 }

} class RadioButtonUtils {

 private RadioButtonUtils() {
   // private constructor so you can"t create instances
 }
 public static Enumeration getSelectedElements(Container container) {
   Vector selections = new Vector();
   Component components[] = container.getComponents();
   for (int i = 0, n = components.length; i < n; i++) {
     if (components[i] instanceof AbstractButton) {
       AbstractButton button = (AbstractButton) components[i];
       if (button.isSelected()) {
         selections.addElement(button.getText());
       }
     }
   }
   return selections.elements();
 }
 public static Container createRadioButtonGrouping(String elements[]) {
   return createRadioButtonGrouping(elements, null, null, null, null);
 }
 public static Container createRadioButtonGrouping(String elements[],
     String title) {
   return createRadioButtonGrouping(elements, title, null, null, null);
 }
 public static Container createRadioButtonGrouping(String elements[],
     String title, ItemListener itemListener) {
   return createRadioButtonGrouping(elements, title, null, itemListener,
       null);
 }
 public static Container createRadioButtonGrouping(String elements[],
     String title, ActionListener actionListener) {
   return createRadioButtonGrouping(elements, title, actionListener, null,
       null);
 }
 public static Container createRadioButtonGrouping(String elements[],
     String title, ActionListener actionListener,
     ItemListener itemListener) {
   return createRadioButtonGrouping(elements, title, actionListener,
       itemListener, null);
 }
 public static Container createRadioButtonGrouping(String elements[],
     String title, ActionListener actionListener,
     ItemListener itemListener, ChangeListener changeListener) {
   JPanel panel = new JPanel(new GridLayout(0, 1));
   //   If title set, create titled border
   if (title != null) {
     Border border = BorderFactory.createTitledBorder(title);
     panel.setBorder(border);
   }
   //   Create group
   ButtonGroup group = new ButtonGroup();
   JRadioButton aRadioButton;
   //   For each String passed in:
   //   Create button, add to panel, and add to group
   for (int i = 0, n = elements.length; i < n; i++) {
     aRadioButton = new JRadioButton(elements[i]);
     panel.add(aRadioButton);
     group.add(aRadioButton);
     if (actionListener != null) {
       aRadioButton.addActionListener(actionListener);
     }
     if (itemListener != null) {
       aRadioButton.addItemListener(itemListener);
     }
     if (changeListener != null) {
       aRadioButton.addChangeListener(changeListener);
     }
   }
   return panel;
 }

}


 </source>
   
  
 
  



Add PopupMenu

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; 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.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.KeyStroke; /* PopupMenuDemo.java is a 1.4 application that requires images/middle.gif. */ /*

* Like MenuDemo, but with popup menus added.
*/

public class PopupMenuDemo implements ActionListener, ItemListener {

 JTextArea output;
 JScrollPane scrollPane;
 String newline = "\n";
 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");
   menuItem.addActionListener(this);
   menu.add(menuItem);
   ImageIcon icon = createImageIcon("images/1.gif");
   menuItem = new JMenuItem("Both text and icon", icon);
   menuItem.setMnemonic(KeyEvent.VK_B);
   menuItem.addActionListener(this);
   menu.add(menuItem);
   menuItem = new JMenuItem(icon);
   menuItem.setMnemonic(KeyEvent.VK_D);
   menuItem.addActionListener(this);
   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);
   rbMenuItem.addActionListener(this);
   menu.add(rbMenuItem);
   rbMenuItem = new JRadioButtonMenuItem("Another one");
   rbMenuItem.setMnemonic(KeyEvent.VK_O);
   group.add(rbMenuItem);
   rbMenuItem.addActionListener(this);
   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);
   cbMenuItem.addItemListener(this);
   menu.add(cbMenuItem);
   cbMenuItem = new JCheckBoxMenuItem("Another one");
   cbMenuItem.setMnemonic(KeyEvent.VK_H);
   cbMenuItem.addItemListener(this);
   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));
   menuItem.addActionListener(this);
   submenu.add(menuItem);
   menuItem = new JMenuItem("Another item");
   menuItem.addActionListener(this);
   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;
 }
 public void createPopupMenu() {
   JMenuItem menuItem;
   //Create the popup menu.
   JPopupMenu popup = new JPopupMenu();
   menuItem = new JMenuItem("A popup menu item");
   menuItem.addActionListener(this);
   popup.add(menuItem);
   menuItem = new JMenuItem("Another popup menu item");
   menuItem.addActionListener(this);
   popup.add(menuItem);
   //Add listener to the text area so the popup menu can come up.
   MouseListener popupListener = new PopupListener(popup);
   output.addMouseListener(popupListener);
 }
 public void actionPerformed(ActionEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Action event detected." + newline + "    Event source: "
       + source.getText() + " (an instance of " + getClassName(source)
       + ")";
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 public void itemStateChanged(ItemEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Item event detected."
       + newline
       + "    Event source: "
       + source.getText()
       + " (an instance of "
       + getClassName(source)
       + ")"
       + newline
       + "    New state: "
       + ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
           : "unselected");
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 // Returns just the class name -- no package info.
 protected String getClassName(Object o) {
   String classString = o.getClass().getName();
   int dotIndex = classString.lastIndexOf(".");
   return classString.substring(dotIndex + 1);
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path) {
   java.net.URL imgURL = PopupMenuDemo.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() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("PopupMenuDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create/set menu bar and content pane.
   PopupMenuDemo demo = new PopupMenuDemo();
   frame.setJMenuBar(demo.createMenuBar());
   frame.setContentPane(demo.createContentPane());
   //Create and set up the popup menu.
   demo.createPopupMenu();
   //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();
     }
   });
 }
 class PopupListener extends MouseAdapter {
   JPopupMenu popup;
   PopupListener(JPopupMenu popupMenu) {
     popup = popupMenu;
   }
   public void mousePressed(MouseEvent e) {
     maybeShowPopup(e);
   }
   public void mouseReleased(MouseEvent e) {
     maybeShowPopup(e);
   }
   private void maybeShowPopup(MouseEvent e) {
     if (e.isPopupTrigger()) {
       popup.show(e.getComponent(), e.getX(), e.getY());
     }
   }
 }

}


 </source>
   
  
 
  



An example of the JPopupMenu in action

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// MenuElementExample.java // An example of the JPopupMenu in action. // import java.awt.ruponent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import javax.swing.JSlider; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.border.rupoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.TitledBorder; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; public class MenuElementExample extends JPanel {

 public JPopupMenu popup;
 SliderMenuItem slider;
 int theValue = 0;
 public MenuElementExample() {
   popup = new JPopupMenu();
   slider = new SliderMenuItem();
   popup.add(slider);
   popup.add(new JSeparator());
   JMenuItem ticks = new JCheckBoxMenuItem("Slider Tick Marks");
   ticks.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       slider.setPaintTicks(!slider.getPaintTicks());
     }
   });
   JMenuItem labels = new JCheckBoxMenuItem("Slider Labels");
   labels.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       slider.setPaintLabels(!slider.getPaintLabels());
     }
   });
   popup.add(ticks);
   popup.add(labels);
   popup.addPopupMenuListener(new PopupPrintListener());
   addMouseListener(new MousePopupListener());
 }
 // Inner class to check whether mouse events are the popup trigger
 class MousePopupListener extends MouseAdapter {
   public void mousePressed(MouseEvent e) {
     checkPopup(e);
   }
   public void mouseClicked(MouseEvent e) {
     checkPopup(e);
   }
   public void mouseReleased(MouseEvent e) {
     checkPopup(e);
   }
   private void checkPopup(MouseEvent e) {
     if (e.isPopupTrigger()) {
       popup.show(MenuElementExample.this, e.getX(), e.getY());
     }
   }
 }
 // Inner class to print information in response to popup events
 class PopupPrintListener implements PopupMenuListener {
   public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
   }
   public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
     theValue = slider.getValue();
     System.out.println("The value is now " + theValue);
   }
   public void popupMenuCanceled(PopupMenuEvent e) {
     System.out.println("Popup menu is hidden!");
   }
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("Menu Element Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new MenuElementExample());
   frame.setSize(300, 300);
   frame.setVisible(true);
 }
 // Inner class that defines our special slider menu item
 class SliderMenuItem extends JSlider implements MenuElement {
   public SliderMenuItem() {
     setBorder(new CompoundBorder(new TitledBorder("Control"),
         new EmptyBorder(10, 10, 10, 10)));
     setMajorTickSpacing(20);
     setMinorTickSpacing(10);
   }
   public void processMouseEvent(MouseEvent e, MenuElement path[],
       MenuSelectionManager manager) {
   }
   public void processKeyEvent(KeyEvent e, MenuElement path[],
       MenuSelectionManager manager) {
   }
   public void menuSelectionChanged(boolean isIncluded) {
   }
   public MenuElement[] getSubElements() {
     return new MenuElement[0];
   }
   public Component getComponent() {
     return this;
   }
 }

}


 </source>
   
  
 
  



A quick demonstration of checkbox menu items

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// CheckBoxMenuItemExample.java // A quick demonstration of checkbox menu items. // import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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.JTextPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.border.BevelBorder; public class CheckBoxMenuItemExample extends JPanel {

 public JTextPane pane;
 public JMenuBar menuBar;
 public JToolBar toolBar;
 public CheckBoxMenuItemExample() {
   menuBar = new JMenuBar();
   JMenu justifyMenu = new JMenu("Justify");
   ActionListener actionPrinter = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       try {
         pane.getStyledDocument().insertString(
             0,
             "Action [" + e.getActionCommand()
                 + "] performed!\n", null);
       } catch (Exception ex) {
         ex.printStackTrace();
       }
     }
   };
   JCheckBoxMenuItem leftJustify = new JCheckBoxMenuItem("Left",
       new ImageIcon("1.gif"));
   leftJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
   leftJustify.setAccelerator(KeyStroke.getKeyStroke("L", Toolkit
       .getDefaultToolkit().getMenuShortcutKeyMask()));
   leftJustify.addActionListener(actionPrinter);
   JCheckBoxMenuItem rightJustify = new JCheckBoxMenuItem("Right",
       new ImageIcon("2.gif"));
   rightJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
   rightJustify.setAccelerator(KeyStroke.getKeyStroke("R", Toolkit
       .getDefaultToolkit().getMenuShortcutKeyMask()));
   rightJustify.addActionListener(actionPrinter);
   JCheckBoxMenuItem centerJustify = new JCheckBoxMenuItem("Center",
       new ImageIcon("3.gif"));
   centerJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
   centerJustify.setAccelerator(KeyStroke.getKeyStroke("M", Toolkit
       .getDefaultToolkit().getMenuShortcutKeyMask()));
   centerJustify.addActionListener(actionPrinter);
   JCheckBoxMenuItem fullJustify = new JCheckBoxMenuItem("Full",
       new ImageIcon("4.gif"));
   fullJustify.setHorizontalTextPosition(JMenuItem.RIGHT);
   fullJustify.setAccelerator(KeyStroke.getKeyStroke("F", Toolkit
       .getDefaultToolkit().getMenuShortcutKeyMask()));
   fullJustify.addActionListener(actionPrinter);
   justifyMenu.add(leftJustify);
   justifyMenu.add(rightJustify);
   justifyMenu.add(centerJustify);
   justifyMenu.add(fullJustify);
   menuBar.add(justifyMenu);
   menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
 }
 public static void main(String s[]) {
   CheckBoxMenuItemExample example = new CheckBoxMenuItemExample();
   example.pane = new JTextPane();
   example.pane.setPreferredSize(new Dimension(250, 250));
   example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
   JFrame frame = new JFrame("Menu Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setJMenuBar(example.menuBar);
   frame.getContentPane().add(example.pane, BorderLayout.CENTER);
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



A simple example of constructing and using menus.

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// MenuExample.java // A simple example of constructing and using menus. // import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; 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.JPanel; import javax.swing.JTextPane; import javax.swing.border.BevelBorder; public class MenuExample extends JPanel {

 public JTextPane pane;
 public JMenuBar menuBar;
 public MenuExample() {
   menuBar = new JMenuBar();
   JMenu formatMenu = new JMenu("Justify");
   formatMenu.setMnemonic("J");
   MenuAction leftJustifyAction = new MenuAction("Left", new ImageIcon(
       "1.gif"));
   MenuAction rightJustifyAction = new MenuAction("Right", new ImageIcon(
       "2.gif"));
   MenuAction centerJustifyAction = new MenuAction("Center",
       new ImageIcon("3.gif"));
   MenuAction fullJustifyAction = new MenuAction("Full", new ImageIcon(
       "4.gif"));
   JMenuItem item;
   item = formatMenu.add(leftJustifyAction);
   item.setMnemonic("L");
   item = formatMenu.add(rightJustifyAction);
   item.setMnemonic("R");
   item = formatMenu.add(centerJustifyAction);
   item.setMnemonic("C");
   item = formatMenu.add(fullJustifyAction);
   item.setMnemonic("F");
   menuBar.add(formatMenu);
   menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
 }
 class MenuAction extends AbstractAction {
   public MenuAction(String text, Icon icon) {
     super(text, icon);
   }
   public void actionPerformed(ActionEvent e) {
     try {
       pane.getStyledDocument().insertString(0,
           "Action [" + e.getActionCommand() + "] performed!\n",
           null);
     } catch (Exception ex) {
       ex.printStackTrace();
     }
   }
 }
 public static void main(String s[]) {
   MenuExample example = new MenuExample();
   example.pane = new JTextPane();
   example.pane.setPreferredSize(new Dimension(250, 250));
   example.pane.setBorder(new BevelBorder(BevelBorder.LOWERED));
   JFrame frame = new JFrame("Menu Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setJMenuBar(example.menuBar);
   frame.getContentPane().add(example.pane, BorderLayout.CENTER);
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



A simple example of JPopupMenu

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// PopupMenuExample.java // A simple example of JPopupMenu. // import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.border.BevelBorder; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; public class PopupMenuExample extends JPanel {

 public JPopupMenu popup;
 public PopupMenuExample() {
   popup = new JPopupMenu();
   ActionListener menuListener = new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       System.out.println("Popup menu item ["
           + event.getActionCommand() + "] was pressed.");
     }
   };
   JMenuItem item;
   popup.add(item = new JMenuItem("Left", new ImageIcon("1.gif")));
   item.setHorizontalTextPosition(JMenuItem.RIGHT);
   item.addActionListener(menuListener);
   popup.add(item = new JMenuItem("Center", new ImageIcon("2.gif")));
   item.setHorizontalTextPosition(JMenuItem.RIGHT);
   item.addActionListener(menuListener);
   popup.add(item = new JMenuItem("Right", new ImageIcon("3.gif")));
   item.setHorizontalTextPosition(JMenuItem.RIGHT);
   item.addActionListener(menuListener);
   popup.add(item = new JMenuItem("Full", new ImageIcon("4.gif")));
   item.setHorizontalTextPosition(JMenuItem.RIGHT);
   item.addActionListener(menuListener);
   popup.addSeparator();
   popup.add(item = new JMenuItem("Settings . . ."));
   item.addActionListener(menuListener);
   popup.setLabel("Justification");
   popup.setBorder(new BevelBorder(BevelBorder.RAISED));
   popup.addPopupMenuListener(new PopupPrintListener());
   addMouseListener(new MousePopupListener());
 }
 // An inner class to check whether mouse events are the popup trigger
 class MousePopupListener extends MouseAdapter {
   public void mousePressed(MouseEvent e) {
     checkPopup(e);
   }
   public void mouseClicked(MouseEvent e) {
     checkPopup(e);
   }
   public void mouseReleased(MouseEvent e) {
     checkPopup(e);
   }
   private void checkPopup(MouseEvent e) {
     if (e.isPopupTrigger()) {
       popup.show(PopupMenuExample.this, e.getX(), e.getY());
     }
   }
 }
 // An inner class to show when popup events occur
 class PopupPrintListener implements PopupMenuListener {
   public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
     System.out.println("Popup menu will be visible!");
   }
   public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
     System.out.println("Popup menu will be invisible!");
   }
   public void popupMenuCanceled(PopupMenuEvent e) {
     System.out.println("Popup menu is hidden!");
   }
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("Popup Menu Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setContentPane(new PopupMenuExample());
   frame.setSize(300, 300);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Building menus and menu items: Accelerators and mnemonics

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// IntroExample.java // An introduction to building menus and menu items. Accelerators and // mnemonics are added to various items. // import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; 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.JRadioButtonMenuItem; import javax.swing.KeyStroke; public class IntroExample extends JMenuBar {

 String[] fileItems = new String[] { "New", "Open", "Save", "Exit" };
 String[] editItems = new String[] { "Undo", "Cut", "Copy", "Paste" };
 char[] fileShortcuts = { "N", "O", "S", "X" };
 char[] editShortcuts = { "Z", "X", "C", "V" };
 public IntroExample() {
   JMenu fileMenu = new JMenu("File");
   JMenu editMenu = new JMenu("Edit");
   JMenu otherMenu = new JMenu("Other");
   JMenu subMenu = new JMenu("SubMenu");
   JMenu subMenu2 = new JMenu("SubMenu2");
   //  Assemble the File menus with mnemonics
   ActionListener printListener = new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       System.out.println("Menu item [" + event.getActionCommand()
           + "] was pressed.");
     }
   };
   for (int i = 0; i < fileItems.length; i++) {
     JMenuItem item = new JMenuItem(fileItems[i], fileShortcuts[i]);
     item.addActionListener(printListener);
     fileMenu.add(item);
   }
   //  Assemble the File menus with keyboard accelerators
   for (int i = 0; i < editItems.length; i++) {
     JMenuItem item = new JMenuItem(editItems[i]);
     item.setAccelerator(KeyStroke
         .getKeyStroke(editShortcuts[i], Toolkit.getDefaultToolkit()
             .getMenuShortcutKeyMask(), false));
     item.addActionListener(printListener);
     editMenu.add(item);
   }
   //  Insert a separator in the Edit Menu in Position 1 after "Undo"
   editMenu.insertSeparator(1);
   //  Assemble the submenus of the Other Menu
   JMenuItem item;
   subMenu2.add(item = new JMenuItem("Extra 2"));
   item.addActionListener(printListener);
   subMenu.add(item = new JMenuItem("Extra 1"));
   item.addActionListener(printListener);
   subMenu.add(subMenu2);
   //  Assemble the Other Menu itself
   otherMenu.add(subMenu);
   otherMenu.add(item = new JCheckBoxMenuItem("Check Me"));
   item.addActionListener(printListener);
   otherMenu.addSeparator();
   ButtonGroup buttonGroup = new ButtonGroup();
   otherMenu.add(item = new JRadioButtonMenuItem("Radio 1"));
   item.addActionListener(printListener);
   buttonGroup.add(item);
   otherMenu.add(item = new JRadioButtonMenuItem("Radio 2"));
   item.addActionListener(printListener);
   buttonGroup.add(item);
   otherMenu.addSeparator();
   otherMenu.add(item = new JMenuItem("Potted Plant", new ImageIcon(
       "image.gif")));
   item.addActionListener(printListener);
   //  Finally, add all the menus to the menu bar
   add(fileMenu);
   add(editMenu);
   add(otherMenu);
 }
 public static void main(String s[]) {
   JFrame frame = new JFrame("Simple Menu Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setJMenuBar(new IntroExample());
   frame.pack();
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



CheckBox Menu Sample

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.Color; import java.awt.ruponent; import java.awt.Graphics; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.AbstractButton; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.UIManager; public class CheckBoxSample {

 static Icon boyIcon = new ImageIcon("boy-r.jpg");
 static Icon girlIcon = new ImageIcon("girl-r.jpg");
 public static void main(String args[]) {
   ActionListener aListener = new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       AbstractButton aButton = (AbstractButton) event.getSource();
       boolean selected = aButton.getModel().isSelected();
       String newLabel;
       Icon newIcon;
       if (selected) {
         newLabel = "Girl";
         newIcon = girlIcon;
       } else {
         newLabel = "Boy";
         newIcon = boyIcon;
       }
       aButton.setText(newLabel);
       aButton.setIcon(newIcon);
     }
   };
   ItemListener iListener = new ItemListener() {
     public void itemStateChanged(ItemEvent event) {
       AbstractButton aButton = (AbstractButton) event.getSource();
       int state = event.getStateChange();
       String newLabel;
       Icon newIcon;
       if (state == ItemEvent.SELECTED) {
         newLabel = "Girl";
         newIcon = girlIcon;
       } else {
         newLabel = "Boy";
         newIcon = boyIcon;
       }
       aButton.setText(newLabel);
       aButton.setIcon(newIcon);
     }
   };
   JFrame frame = new JFrame("CheckBox Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new JMenuBar();
   JMenu menu = new JMenu("Menu");
   menu.setMnemonic(KeyEvent.VK_M);
   JCheckBoxMenuItem one = new JCheckBoxMenuItem();
   menu.add(one);
   JCheckBoxMenuItem two = new JCheckBoxMenuItem("Boy");
   menu.add(two);
   JCheckBoxMenuItem three = new JCheckBoxMenuItem(boyIcon);
   menu.add(three);
   JCheckBoxMenuItem four = new JCheckBoxMenuItem("Girl", true);
   menu.add(four);
   JCheckBoxMenuItem five = new JCheckBoxMenuItem("Boy", boyIcon);
   five.addItemListener(iListener);
   menu.add(five);
   Icon stateIcon = new DiamondAbstractButtonStateIcon(Color.black);
   UIManager.put("CheckBoxMenuItem.checkIcon", stateIcon);
   JCheckBoxMenuItem six = new JCheckBoxMenuItem("Girl", girlIcon, true);
   six.addActionListener(aListener);
   menu.add(six);
   bar.add(menu);
   frame.setJMenuBar(bar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class DiamondAbstractButtonStateIcon implements Icon {

 private final int width = 10;
 private final int height = 10;
 private Color color;
 private Polygon polygon;
 public DiamondAbstractButtonStateIcon(Color color) {
   this.color = color;
   initPolygon();
 }
 private void initPolygon() {
   polygon = new Polygon();
   int halfWidth = width / 2;
   int halfHeight = height / 2;
   polygon.addPoint(0, halfHeight);
   polygon.addPoint(halfWidth, 0);
   polygon.addPoint(width, halfHeight);
   polygon.addPoint(halfWidth, height);
 }
 public int getIconHeight() {
   return width;
 }
 public int getIconWidth() {
   return height;
 }
 public void paintIcon(Component component, Graphics g, int x, int y) {
   boolean selected = false;
   g.setColor(color);
   g.translate(x, y);
   if (component instanceof AbstractButton) {
     AbstractButton abstractButton = (AbstractButton) component;
     selected = abstractButton.isSelected();
   }
   if (selected) {
     g.fillPolygon(polygon);
   } else {
     g.drawPolygon(polygon);
   }
   g.translate(-x, -y);
 }

}


 </source>
   
  
 
  



Color Menu

   <source lang="java">
  

/*

    • Salsa - Swing Add-On Suite
    • Copyright (c) 2001, 2002 by Gerald Bauer
    • This program is free software.
    • You may redistribute it and/or modify it under the terms of the GNU
    • General Public License as published by the Free Software Foundation.
    • Version 2 of the license should be included with this distribution in
    • the file LICENSE, as well as License.html. If the license is not
    • included with this distribution, you may find a copy at the FSF web
    • site at "www.gnu.org" or "www.fsf.org", or you may write to the
    • Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139 USA.
    • THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
    • NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
    • OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
    • CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
    • REDISTRIBUTION OF THIS SOFTWARE.
  • /

import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; public class ColorMenu extends JMenu {

  Border _activeBorder;
  Map _colorPanes;
  Border _selectedBorder;
  ColorPane _selectedColorPane;
  Border _unselectedBorder;
  public ColorMenu( String name )
  {
     super( name );
     _unselectedBorder = new CompoundBorder(
           new MatteBorder( 1, 1, 1, 1, getBackground() ),
           new BevelBorder( BevelBorder.LOWERED, Color.WHITE, Color.GRAY ) );
     _selectedBorder = new CompoundBorder(
           new MatteBorder( 2, 2, 2, 2, Color.RED ),
           new MatteBorder( 1, 1, 1, 1, getBackground() ) );
     _activeBorder = new CompoundBorder(
           new MatteBorder( 2, 2, 2, 2, Color.BLUE ),
           new MatteBorder( 1, 1, 1, 1, getBackground() ) );
     JPanel p = new JPanel();
     p.setBorder( new EmptyBorder( 5, 5, 5, 5 ) );
     p.setLayout( new GridLayout( 8, 8 ) );
     _colorPanes = new HashMap();
     int values[] = new int[]{0, 128, 192, 255};
     for( int r = 0; r < values.length; r++ )
        for( int g = 0; g < values.length; g++ )
           for( int b = 0; b < values.length; b++ )
           {
              Color color = new Color( values[r], values[g], values[b] );
              ColorPane colorPane = new ColorPane( color );
              p.add( colorPane );
              _colorPanes.put( color, colorPane );
           }
     add( p );
  }
  public void setColor( Color c )
  {
     Object obj = _colorPanes.get( c );
     if( obj == null )
        return;
     if( _selectedColorPane != null )
        _selectedColorPane.setSelected( false );
     _selectedColorPane = ( ColorPane ) obj;
     _selectedColorPane.setSelected( true );
  }
  public Color getColor()
  {
     if( _selectedColorPane == null )
        return null;
     return _selectedColorPane.getColor();
  }
  public void doSelection()
  {
     fireActionPerformed( new ActionEvent( this,
           ActionEvent.ACTION_PERFORMED, getActionCommand() ) );
  }
  class ColorPane extends JPanel implements MouseListener
  {
     Color _color;
     boolean _isSelected;
     public ColorPane( Color color )
     {
        _color = color;
        setBackground( color );
        setBorder( _unselectedBorder );
        String msg = "rgb( " + color.getRed() + ", "
               + color.getGreen() + ", "
               + color.getBlue() + " )";
        setToolTipText( msg );
        addMouseListener( this );
     }
     public void setSelected( boolean isSelected )
     {
        _isSelected = isSelected;
        if( _isSelected )
           setBorder( _selectedBorder );
        else
           setBorder( _unselectedBorder );
     }
     public Color getColor()
     {
        return _color;
     }
     public Dimension getMaximumSize()
     {
        return getPreferredSize();
     }
     public Dimension getMinimumSize()
     {
        return getPreferredSize();
     }
     public Dimension getPreferredSize()
     {
        return new Dimension( 15, 15 );
     }
     public boolean isSelected()
     {
        return _isSelected;
     }
     public void mouseClicked( MouseEvent ev ) { }
     public void mouseEntered( MouseEvent ev )
     {
        setBorder( _activeBorder );
     }
     public void mouseExited( MouseEvent ev )
     {
        setBorder( _isSelected ? _selectedBorder : _unselectedBorder );
     }
     public void mousePressed( MouseEvent ev ) { }
     public void mouseReleased( MouseEvent ev )
     {
        setColor( _color );
        MenuSelectionManager.defaultManager().clearSelectedPath();
        doSelection();
     }
  }

}


 </source>
   
  
 
  



Comprehensive Menu Demo

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.Icon; 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.JRadioButtonMenuItem; import javax.swing.KeyStroke; public class MediumPopupSample {

 static class MenuActionListener implements ActionListener {
   public void actionPerformed(ActionEvent actionEvent) {
     System.out.println("Selected: " + actionEvent.getActionCommand());
   }
 }
 public static void main(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);
   // File->Open, O - Mnemonic
   JMenuItem openMenuItem = new JMenuItem("Open", KeyEvent.VK_O);
   openMenuItem.addActionListener(menuListener);
   fileMenu.add(openMenuItem);
   // File->Close, C - Mnemonic
   JMenuItem closeMenuItem = new JMenuItem("Close", KeyEvent.VK_C);
   closeMenuItem.addActionListener(menuListener);
   fileMenu.add(closeMenuItem);
   // Separator
   fileMenu.addSeparator();
   // File->Save, S - Mnemonic
   JMenuItem saveMenuItem = new JMenuItem("Save", KeyEvent.VK_S);
   saveMenuItem.addActionListener(menuListener);
   fileMenu.add(saveMenuItem);
   // Separator
   fileMenu.addSeparator();
   // File->Exit, X - Mnemonic
   JMenuItem exitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X);
   exitMenuItem.addActionListener(menuListener);
   fileMenu.add(exitMenuItem);
   // Edit Menu, E - Mnemonic
   JMenu editMenu = new JMenu("Edit");
   editMenu.setMnemonic(KeyEvent.VK_E);
   menuBar.add(editMenu);
   // Edit->Cut, T - Mnemonic, CTRL-X - Accelerator
   JMenuItem cutMenuItem = new JMenuItem("Cut", KeyEvent.VK_T);
   cutMenuItem.addActionListener(menuListener);
   KeyStroke ctrlXKeyStroke = KeyStroke.getKeyStroke("control X");
   cutMenuItem.setAccelerator(ctrlXKeyStroke);
   editMenu.add(cutMenuItem);
   // Edit->Copy, C - Mnemonic, CTRL-C - Accelerator
   JMenuItem copyMenuItem = new JMenuItem("Copy", KeyEvent.VK_C);
   copyMenuItem.addActionListener(menuListener);
   KeyStroke ctrlCKeyStroke = KeyStroke.getKeyStroke("control C");
   copyMenuItem.setAccelerator(ctrlCKeyStroke);
   editMenu.add(copyMenuItem);
   // Edit->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled
   JMenuItem pasteMenuItem = new JMenuItem("Paste", KeyEvent.VK_P);
   pasteMenuItem.addActionListener(menuListener);
   KeyStroke ctrlVKeyStroke = KeyStroke.getKeyStroke("control V");
   pasteMenuItem.setAccelerator(ctrlVKeyStroke);
   pasteMenuItem.setEnabled(false);
   editMenu.add(pasteMenuItem);
   // Separator
   editMenu.addSeparator();
   // Edit->Find, F - Mnemonic, F3 - Accelerator
   JMenuItem findMenuItem = new JMenuItem("Find", KeyEvent.VK_F);
   findMenuItem.addActionListener(menuListener);
   KeyStroke f3KeyStroke = KeyStroke.getKeyStroke("F3");
   findMenuItem.setAccelerator(f3KeyStroke);
   editMenu.add(findMenuItem);
   // 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);
   // ButtonGroup for radio buttons
   ButtonGroup directionGroup = new ButtonGroup();
   // Edit->Options->Forward, F - Mnemonic, in group
   JRadioButtonMenuItem forwardMenuItem = new JRadioButtonMenuItem(
       "Forward", true);
   forwardMenuItem.addActionListener(menuListener);
   forwardMenuItem.setMnemonic(KeyEvent.VK_F);
   findOptionsMenu.add(forwardMenuItem);
   directionGroup.add(forwardMenuItem);
   // Edit->Options->Backward, B - Mnemonic, in group
   JRadioButtonMenuItem backwardMenuItem = new JRadioButtonMenuItem(
       "Backward");
   backwardMenuItem.addActionListener(menuListener);
   backwardMenuItem.setMnemonic(KeyEvent.VK_B);
   findOptionsMenu.add(backwardMenuItem);
   directionGroup.add(backwardMenuItem);
   // Separator
   findOptionsMenu.addSeparator();
   // Edit->Options->Case Sensitive, C - Mnemonic
   JCheckBoxMenuItem caseMenuItem = new JCheckBoxMenuItem("Case Sensitive");
   caseMenuItem.addActionListener(menuListener);
   caseMenuItem.setMnemonic(KeyEvent.VK_C);
   findOptionsMenu.add(caseMenuItem);
   editMenu.add(findOptionsMenu);
   frame.setJMenuBar(menuBar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Create a change listener and register with the menu selection manager

   <source lang="java">
 

import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Main {

 public static void main(String[] argv) throws Exception {
   MenuSelectionManager.defaultManager().addChangeListener(
       new ChangeListener() {
         public void stateChanged(ChangeEvent evt) {
           MenuSelectionManager msm = (MenuSelectionManager) evt.getSource();
           MenuElement[] path = msm.getSelectedPath();
           if (path.length == 0) {
           }
         }
       });
 }

}


 </source>
   
  
 
  



Create a main menu.

   <source lang="java">
 

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

 Main() {
   JFrame f = new JFrame("Menu Demo");
   f.setSize(220, 200);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar jmb = new JMenuBar();
   JMenu jmFile = new JMenu("File");
   JMenuItem jmiOpen = new JMenuItem("Open");
   JMenuItem jmiClose = new JMenuItem("Close");
   JMenuItem jmiSave = new JMenuItem("Save");
   JMenuItem jmiExit = new JMenuItem("Exit");
   jmFile.add(jmiOpen);
   jmFile.add(jmiClose);
   jmFile.add(jmiSave);
   jmFile.addSeparator();
   jmFile.add(jmiExit);
   jmb.add(jmFile);
   JMenu jmOptions = new JMenu("Options");
   JMenu a = new JMenu("A");
   JMenuItem b = new JMenuItem("B");
   JMenuItem c = new JMenuItem("C");
   JMenuItem d = new JMenuItem("D");
   a.add(b);
   a.add(c);
   a.add(d);
   jmOptions.add(a);
   JMenu e = new JMenu("E");
   e.add(new JMenuItem("F"));
   e.add(new JMenuItem("G"));
   jmOptions.add(e);
   jmb.add(jmOptions);
   JMenu jmHelp = new JMenu("Help");
   JMenuItem jmiAbout = new JMenuItem("About");
   jmHelp.add(jmiAbout);
   jmb.add(jmHelp);
   jmiOpen.addActionListener(this);
   jmiClose.addActionListener(this);
   jmiSave.addActionListener(this);
   jmiExit.addActionListener(this);
   b.addActionListener(this);
   c.addActionListener(this);
   d.addActionListener(this);
   jmiAbout.addActionListener(this);
   f.setJMenuBar(jmb);
   f.setVisible(true);
 }
 public void actionPerformed(ActionEvent ae) {
   String comStr = ae.getActionCommand();
   System.out.println(comStr + " Selected");
 }
 public static void main(String args[]) {
   new Main();
 }

}


 </source>
   
  
 
  



Creating a JMenuBar, JMenu, and JMenuItem Component

   <source lang="java">
 

import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class Main {

 public static void main(String[] argv) throws Exception {
   // Create the menu bar
   JMenuBar menuBar = new JMenuBar();
   // Create a menu
   JMenu menu = new JMenu("Menu Label");
   menuBar.add(menu);
   // Create a menu item
   JMenuItem item = new JMenuItem("Item Label");
   //item.addActionListener(actionListener);
   menu.add(item);
   JFrame frame = new JFrame();
   // Install the menu bar in the frame
   frame.setJMenuBar(menuBar);
 }

}


 </source>
   
  
 
  



Creating a menubar

   <source lang="java">
 

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class MenuMy extends JFrame {

 JMenuBar menubar = new JMenuBar();
 ImageIcon icon = new ImageIcon("exit.png");
 JMenu file = new JMenu("File");
 public MenuMy() {
   file.setMnemonic(KeyEvent.VK_F);
   JMenuItem fileClose = new JMenuItem("Close", icon);
   fileClose.setMnemonic(KeyEvent.VK_C);
   fileClose.setToolTipText("Exit application");
   fileClose.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       System.exit(0);
     }
   });
   file.add(fileClose);
   menubar.add(file);
   setJMenuBar(menubar);
   setSize(250, 200);
   setDefaultCloseOperation(EXIT_ON_CLOSE);
   setVisible(true);
 }
 public static void main(String[] args) {
   new MenuMy();
 }

}


 </source>
   
  
 
  



Creating a Menu Item That Listens for Changes to Its Selection Status

   <source lang="java">
 

import javax.swing.JMenuItem; public class Main {

 public static void main(String[] argv) throws Exception {
   JMenuItem item = new JMenuItem("Label") {
     public void menuSelectionChanged(boolean isSelected) {
       super.menuSelectionChanged(isSelected);
       if (isSelected) {
         System.out.println("The menu item is selected"); 
       } else {
         System.out.println("The menu item is no longer selected"); 
       }
     }
   };
 }

}


 </source>
   
  
 
  



Creating popup menus with Swing

   <source lang="java">
 

// : c14:Popup.java // Creating popup menus with Swing. // <applet code=Popup width=300 height=200></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTextField; public class Popup extends JApplet {

 private JPopupMenu popup = new JPopupMenu();
 private JTextField t = new JTextField(10);
 public void init() {
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   cp.add(t);
   ActionListener al = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       t.setText(((JMenuItem) e.getSource()).getText());
     }
   };
   JMenuItem m = new JMenuItem("Hither");
   m.addActionListener(al);
   popup.add(m);
   m = new JMenuItem("Yon");
   m.addActionListener(al);
   popup.add(m);
   m = new JMenuItem("Afar");
   m.addActionListener(al);
   popup.add(m);
   popup.addSeparator();
   m = new JMenuItem("Stay Here");
   m.addActionListener(al);
   popup.add(m);
   PopupListener pl = new PopupListener();
   addMouseListener(pl);
   t.addMouseListener(pl);
 }
 class PopupListener extends MouseAdapter {
   public void mousePressed(MouseEvent e) {
     maybeShowPopup(e);
   }
   public void mouseReleased(MouseEvent e) {
     maybeShowPopup(e);
   }
   private void maybeShowPopup(MouseEvent e) {
     if (e.isPopupTrigger())
       popup.show(((JApplet) e.getComponent()).getContentPane(), e
           .getX(), e.getY());
   }
 }
 public static void main(String[] args) {
   run(new Popup(), 300, 200);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~



 </source>
   
  
 
  



Demonstrate Cascading Menus

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; /**

* Demonstrate Cascading Menus for students of Learning Tree Course 471/478
* 
* @author Ian Darwin
*/

public class MenuCascade extends JFrame {

 JMenuBar mb;
 JMenu fm, om, hm; // File, Options, Help
 JMenu opSubm; // Options Sub-Menu
 JMenuItem mi;
 // Constructor
 MenuCascade(String s) {
   super("MenuCascade: " + s);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   mb = new JMenuBar();
   setJMenuBar(mb);
   // The File Menu...
   fm = new JMenu("File");
   fm.add(mi = new JMenuItem("Open"));
   mi.addActionListener(defaultHandler);
   fm.add(mi = new JMenuItem("Close"));
   mi.addActionListener(defaultHandler);
   fm.addSeparator();
   fm.add(mi = new JMenuItem("Exit"));
   mi.addActionListener(defaultHandler);
   mi.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.exit(0);
     }
   });
   mb.add(fm);
   // The Options Menu...
   om = new JMenu("Options");
   opSubm = new JMenu("SubOptions");
   opSubm.add(mi = new JMenuItem("Alpha"));
   mi.addActionListener(defaultHandler);
   opSubm.add(mi = new JMenuItem("Gamma"));
   mi.addActionListener(defaultHandler);
   opSubm.add(mi = new JMenuItem("Delta"));
   mi.addActionListener(defaultHandler);
   om.add(opSubm);
   mb.add(om);
   // The Help Menu...
   hm = new JMenu("Help");
   hm.add(mi = new JMenuItem("About"));
   mi.addActionListener(defaultHandler);
   mi.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       JOptionPane.showMessageDialog(MenuCascade.this, "Version 0",
           "Version 0", JOptionPane.INFORMATION_MESSAGE);
     }
   });
   hm.add(mi = new JMenuItem("Topics"));
   mi.addActionListener(defaultHandler);
   mb.add(hm);
   // the main window

// cp.add(new MyCanvas("Menu Demo Window", 200, 150));

   pack();
 }
 ActionListener defaultHandler = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     System.out.println("You chose " + e.getActionCommand());
   }
 };
 public static void main(String[] arg) {
   MenuCascade mb = new MenuCascade("Testing 1 2 3...");
   mb.setVisible(true);
 }

}


 </source>
   
  
 
  



Demonstrate JMenu shortcuts and accelerators

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.Container; import java.awt.Event; 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; import javax.swing.KeyStroke; /**

* Demonstrate JMenu shortcuts and accelerators.
* 
* @author Ian Darwin, http://www.darwinsys.ru/
* @version $Id: MenuShortcuts.java,v 1.4 2004/02/09 03:33:50 ian Exp $
*/

public class MenuShortcuts extends JFrame implements ActionListener {

 /** The menubar */
 JMenuBar mb;
 /** File, Options, Help */
 JMenu fm, om, hm;
 /** Options Sub-JMenu */
 JMenu opSubm;
 /** The JMenuItem for exiting. */
 JMenuItem exitItem;
 // Constructor
 MenuShortcuts(String s) {
   super("JMenuShortcuts: " + s);
   mb = new JMenuBar();
   setJMenuBar(mb); // Frame implements JMenuContainer
   Container cp = getContentPane();
   JMenuItem mi;
   // The File JMenu...
   fm = new JMenu("File");
   fm.setMnemonic("F");
   fm.add(mi = new JMenuItem("Open", "O"));
   mi.addActionListener(this);
   fm.add(mi = new JMenuItem("Close", "W"));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new JMenuItem("Print", "P"));
   mi
       .setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R,
           Event.ALT_MASK));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new JMenuItem("Exit", "Q"));
   exitItem = mi; // save for action handler
   mi.addActionListener(this);
   mb.add(fm);
   // The Options JMenu...
   om = new JMenu("Options");
   om.add(new JMenuItem("Alpha"));
   om.add(new JMenuItem("Gamma"));
   om.add(new JMenuItem("Delta"));
   mb.add(om);
   // The Help JMenu...
   hm = new JMenu("Help");
   hm.add(mi = new JMenuItem("About"));
   mi.addActionListener(this);
   hm.add(mi = new JMenuItem("Topics"));
   mi.addActionListener(this);
   mb.add(hm);
   // mb.setHelpMenu(hm); // needed for portability (Motif, etc.).
   // the main window
   cp.add(new Label("Menu Demo Window", 200, 150));
   pack();
 }
 /** Handle action events. */
 public void actionPerformed(ActionEvent evt) {
   // System.out.println("Event " + evt);
   String cmd;
   if ((cmd = evt.getActionCommand()) == null)
     System.out.println("You chose a menu shortcut");
   else
     System.out.println("You chose " + cmd);
   Object cmp = evt.getSource();
   // System.out.println("Source " + cmp);
   if (cmp == exitItem)
     System.exit(0);
 }
 public static void main(String[] arg) {
   new MenuShortcuts("Testing 1 2 3...").setVisible(true);
 }

}



 </source>
   
  
 
  



Demonstrate Menus and the MenuBar class

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.CheckboxMenuItem; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.MenuShortcut; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; /**

* Demonstrate Menus and the MenuBar class/MenuContainer interface
* 
* This version uses 1.1 action handling and MenuShortcut. The action handling
* is incomplete; realistically, each MenuItem would have its own, task-specific
* ActionListener; this would handle the MenuShortcuts and the CheckboxMenuItems
* correctly.
* 
* @author Ian Darwin
*/

public class AnotherMenuDemo extends Frame implements ActionListener, ItemListener {

 MenuBar mb;
 /** File, Options, Help */
 Menu fm, om, hm;
 /** Options Sub-Menu */
 Menu opSubm;
 /** The MenuItem for exiting. */
 MenuItem exitItem;
 /** An option that can be on or off. */
 CheckboxMenuItem cb;
 // Constructor
 AnotherMenuDemo(String s) {
   super("MenuDemo: " + s);
   Container cp = this;
   cp.setLayout(new FlowLayout());
   mb = new MenuBar();
   setMenuBar(mb); // Frame implements MenuContainer
   MenuItem mi;
   // The File Menu...
   fm = new Menu("File");
   fm.add(mi = new MenuItem("Open", new MenuShortcut("O")));
   mi.addActionListener(this);
   fm.add(mi = new MenuItem("Close", new MenuShortcut("W")));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new MenuItem("Print", new MenuShortcut("P")));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new MenuItem("Exit", new MenuShortcut("Q")));
   exitItem = mi; // save for action handler
   mi.addActionListener(this);
   mb.add(fm);
   // The Options Menu...
   om = new Menu("Options");
   cb = new CheckboxMenuItem("AutoSave");
   cb.setState(true);
   cb.addItemListener(this);
   om.add(cb);
   opSubm = new Menu("SubOptions");
   opSubm.add(new MenuItem("Alpha"));
   opSubm.add(new MenuItem("Gamma"));
   opSubm.add(new MenuItem("Delta"));
   om.add(opSubm);
   mb.add(om);
   // The Help Menu...
   hm = new Menu("Help");
   hm.add(mi = new MenuItem("About"));
   mi.addActionListener(this);
   hm.add(mi = new MenuItem("Topics"));
   mi.addActionListener(this);
   mb.add(hm);
   mb.setHelpMenu(hm); // needed for portability (Motif, etc.).
   // the main window
   cp.add(new Label("Menu Demo Window", 200, 150));
   pack();
 }
 /** Handle action events. */
 public void actionPerformed(ActionEvent evt) {
   // System.out.println("Event " + evt);
   String cmd;
   if ((cmd = evt.getActionCommand()) == null)
     System.out.println("You chose a menu shortcut");
   else
     System.out.println("You chose " + cmd);
   Object cmp = evt.getSource();
   // System.out.println("Source " + cmp);
   if (cmp == exitItem)
     System.exit(0);
 }
 /** The CheckBoxMenuItems send a different message */
 public void itemStateChanged(ItemEvent e) {
   System.out.println("AutoSave is set " + cb.getState());
 }
 public static void main(String[] arg) {
   new MenuDemo("Testing 1 2 3...").setVisible(true);
 }

}



 </source>
   
  
 
  



Getting the Currently Selected Menu or Menu Item

   <source lang="java">
 

import java.awt.ruponent; import javax.swing.JMenuItem; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; public class Main {

 public static void main(String[] argv) throws Exception {
   MenuElement[] path = MenuSelectionManager.defaultManager()
       .getSelectedPath();
   if (path.length == 0) {
     System.out.println("No menus are opened or menu items selected"); 
   }
   for (int i = 0; i < path.length; i++) {
     Component c = path[i].getComponent();
     if (c instanceof JMenuItem) {
       JMenuItem mi = (JMenuItem) c;
       String label = mi.getText();
     }
   }
 }

}


 </source>
   
  
 
  



How to create customized menu

   <source lang="java">
 

import java.awt.Color; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.Hashtable; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JPanel; import javax.swing.MenuSelectionManager; import javax.swing.border.BevelBorder; import javax.swing.border.Border; import javax.swing.border.rupoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.border.MatteBorder; public class ColorChooserMenu extends JFrame {

 public ColorChooserMenu() {
   super("Color Chooser Menu");
   setSize(450, 350);
   JMenuBar menuBar = createMenuBar();
   setJMenuBar(menuBar);
   WindowListener wndCloser = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(wndCloser);
   setVisible(true);
 }
 protected JMenuBar createMenuBar() {
   final JMenuBar menuBar = new JMenuBar();
   ColorMenu cm = new ColorMenu("Foreground");
   cm.setMnemonic("f");
   ActionListener lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       ColorMenu m = (ColorMenu) e.getSource();
       System.out.println(m.getColor());
     }
   };
   cm.addActionListener(lst);
   menuBar.add(cm);
   return menuBar;
 }
 public static void main(String argv[]) {
   new ColorChooserMenu();
 }

} class ColorMenu extends JMenu {

 protected Border unselectedBorder;
 protected Border selectedBorder;
 protected Border activeBorder;
 protected Hashtable paneTable;
 protected ColorPane colorPane;
 public ColorMenu(String name) {
   super(name);
   unselectedBorder = new CompoundBorder(new MatteBorder(1, 1, 1, 1,
       getBackground()), new BevelBorder(BevelBorder.LOWERED,
       Color.white, Color.gray));
   selectedBorder = new CompoundBorder(new MatteBorder(1, 1, 1, 1,
       Color.red), new MatteBorder(1, 1, 1, 1, getBackground()));
   activeBorder = new CompoundBorder(new MatteBorder(1, 1, 1, 1,
       Color.blue), new MatteBorder(1, 1, 1, 1, getBackground()));
   JPanel p = new JPanel();
   p.setBorder(new EmptyBorder(5, 5, 5, 5));
   p.setLayout(new GridLayout(8, 8));
   paneTable = new Hashtable();
   int[] values = new int[] { 0 ,128, 192, 255 };
   
   for (int r = 0; r < values.length; r++) {
     for (int g = 0; g < values.length; g++) {
       for (int b = 0; b < values.length; b++) {
         Color c = new Color(values[r], values[g], values[b]);
         ColorPane pn = new ColorPane(c);
         p.add(pn);
         paneTable.put(c, pn);
       }
     }
   }
   add(p);
 }
 public void setColor(Color c) {
   Object obj = paneTable.get(c);
   if (obj == null)
     return;
   if (colorPane != null)
     colorPane.setSelected(false);
   colorPane = (ColorPane) obj;
   colorPane.setSelected(true);
 }
 public Color getColor() {
   if (colorPane == null)
     return null;
   return colorPane.getColor();
 }
 public void doSelection() {
   fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED,
       getActionCommand()));
 }
 class ColorPane extends JPanel implements MouseListener {
   protected Color color;
   protected boolean isSelected;
   public ColorPane(Color c) {
     color = c;
     setBackground(c);
     setBorder(unselectedBorder);
     String msg = "R " + c.getRed() + ", G " + c.getGreen() + ", B "
         + c.getBlue();
     setToolTipText(msg);
     addMouseListener(this);
   }
   public Color getColor() {
     return color;
   }
   public Dimension getPreferredSize() {
     return new Dimension(15, 15);
   }
   public Dimension getMaximumSize() {
     return getPreferredSize();
   }
   public Dimension getMinimumSize() {
     return getPreferredSize();
   }
   public void setSelected(boolean selected) {
     isSelected = selected;
     if (isSelected)
       setBorder(selectedBorder);
     else
       setBorder(unselectedBorder);
   }
   public boolean isSelected() {
     return isSelected;
   }
   public void mousePressed(MouseEvent e) {
   }
   public void mouseClicked(MouseEvent e) {
   }
   public void mouseReleased(MouseEvent e) {
     setColor(color);
     MenuSelectionManager.defaultManager().clearSelectedPath();
     doSelection();
   }
   public void mouseEntered(MouseEvent e) {
     setBorder(activeBorder);
   }
   public void mouseExited(MouseEvent e) {
     setBorder(isSelected ? selectedBorder : unselectedBorder);
   }
 }

}


 </source>
   
  
 
  



Listening for Changes to the Currently Selected Menu or Menu Item

   <source lang="java">
 

import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; public class Main {

 public static void main(String[] argv) throws Exception {
   MenuSelectionManager.defaultManager().addChangeListener(
       new ChangeListener() {
         public void stateChanged(ChangeEvent evt) {
           MenuSelectionManager msm = (MenuSelectionManager) evt.getSource();
           MenuElement[] path = msm.getSelectedPath();
           if (path.length == 0) {
           }
         }
       });
 }

}


 </source>
   
  
 
  



Menu Action Screen Dump Demo

   <source lang="java">
 

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class ScreenDump {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Action Sample");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   final Action printAction = new PrintHelloAction();
   JMenuBar menuBar = new JMenuBar();
   JMenu menu = new JMenu("File");
   menuBar.add(menu);
   JMenuItem menuItem = new JMenuItem("Print");
   KeyStroke ctrlP = KeyStroke.getKeyStroke(KeyEvent.VK_P,
       InputEvent.CTRL_MASK);
   menuItem.setAccelerator(ctrlP);
   menuItem.addActionListener(printAction);
   menu.add(menuItem);
   JButton fileButton = new JButton("About");
   fileButton.setMnemonic(KeyEvent.VK_A);
   fileButton.addActionListener(printAction);
   frame.setJMenuBar(menuBar);
   Container contentPane = frame.getContentPane();
   contentPane.add(fileButton, BorderLayout.SOUTH);
   frame.setSize(300, 100);
   frame.setVisible(true);
 }

} class PrintHelloAction extends AbstractAction {

 private static final Icon printIcon = new ImageIcon("Print.gif");
 PrintHelloAction() {
   super("Print", printIcon);
   putValue(Action.SHORT_DESCRIPTION, "Hello World");
 }
 public void actionPerformed(ActionEvent actionEvent) {
   System.out.println("Hello World");
 }

}


 </source>
   
  
 
  



Menu created from property file

   <source lang="java">
 

//Menus.properties /*

  1. The file Menus.properties is the default "Menus" resource bundle.
  2. As an American programmer, I made my own locale the default.

colors.label=Colors colors.red.label=Red colors.red.accelerator=alt R colors.green.label=Green colors.green.accelerator=alt G colors.blue.label=Blue colors.blue.accelerator=alt B

  • /

//Menus_fr.properties /*

  1. This is the file Menus_fr.properties. It is the resource bundle for all
  2. French-speaking locales. It overrides most, but not all, of the resources
  3. in the default bundle.

colors.label=Couleurs colors.red.label=Rouge colors.green.label=Vert colors.green.accelerator=control shift V colors.blue.label=Bleu

  • /

//Menus_en_GB.properties /*

  1. This is the file Menus_en_GB.properties. It is the resource bundle for
  2. British English. Note that it overrides only a single resource definition
  3. and simply inherits the rest from the default (American) bundle.

colors.label=Colours

  • /

/// /*

* Copyright (c) 2000 David Flanagan.  All rights reserved.
* This code is from the book Java Examples in a Nutshell, 2nd Edition.
* It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied.
* You may study, use, and modify it for any non-commercial purpose.
* You may distribute it non-commercially as long as you retain this notice.
* For a commercial use license, or to purchase the book (recommended),
* visit http://www.davidflanagan.ru/javaexamples2.
*/

import java.awt.Color; import java.awt.ruponent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Locale; import java.util.MissingResourceException; import java.util.ResourceBundle; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; /** A convenience class to automatically create localized menu panes */ public class SimpleMenu {

 /** The convenience method that creates menu panes */
 public static JMenu create(ResourceBundle bundle, String menuname,
     String[] itemnames, ActionListener listener) {
   // Get the menu title from the bundle. Use name as default label.
   String menulabel;
   try {
     menulabel = bundle.getString(menuname + ".label");
   } catch (MissingResourceException e) {
     menulabel = menuname;
   }
   // Create the menu pane.
   JMenu menu = new JMenu(menulabel);
   // For each named item in the menu.
   for (int i = 0; i < itemnames.length; i++) {
     // Look up the label for the item, using name as default.
     String itemlabel;
     try {
       itemlabel = bundle.getString(menuname + "." + itemnames[i]
           + ".label");
     } catch (MissingResourceException e) {
       itemlabel = itemnames[i];
     }
     JMenuItem item = new JMenuItem(itemlabel);
     // Look up an accelerator for the menu item
     try {
       String acceleratorText = bundle.getString(menuname + "."
           + itemnames[i] + ".accelerator");
       item.setAccelerator(KeyStroke.getKeyStroke(acceleratorText));
     } catch (MissingResourceException e) {
     }
     // Register an action listener and command for the item.
     if (listener != null) {
       item.addActionListener(listener);
       item.setActionCommand(itemnames[i]);
     }
     // Add the item to the menu.
     menu.add(item);
   }
   // Return the automatically created localized menu.
   return menu;
 }
 /** A simple test program for the above code */
 public static void main(String[] args) {
   // Get the locale: default, or specified on command-line
   Locale locale;
   if (args.length == 2)
     locale = new Locale(args[0], args[1]);
   else
     locale = Locale.getDefault();
   // Get the resource bundle for that Locale. This will throw an
   // (unchecked) MissingResourceException if no bundle is found.
   ResourceBundle bundle = ResourceBundle.getBundle(
       "com.davidflanagan.examples.i18n.Menus", locale);
   // Create a simple GUI window to display the menu with
   final JFrame f = new JFrame("SimpleMenu: " + // Window title
       locale.getDisplayName(Locale.getDefault()));
   JMenuBar menubar = new JMenuBar(); // Create a menubar.
   f.setJMenuBar(menubar); // Add menubar to window
   // Define an action listener for that our menu will use.
   ActionListener listener = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       String s = e.getActionCommand();
       Component c = f.getContentPane();
       if (s.equals("red"))
         c.setBackground(Color.red);
       else if (s.equals("green"))
         c.setBackground(Color.green);
       else if (s.equals("blue"))
         c.setBackground(Color.blue);
     }
   };
   // Now create a menu using our convenience routine with the resource
   // bundle and action listener we"ve created
   JMenu menu = SimpleMenu.create(bundle, "colors", new String[] { "red",
       "green", "blue" }, listener);
   // Finally add the menu to the GUI, and pop it up
   menubar.add(menu); // Add the menu to the menubar
   f.setSize(300, 150); // Set the window size.
   f.setVisible(true); // Pop the window up.
 }

}



 </source>
   
  
 
  



Menu Demo

   <source lang="java">
 

/*

* This example is from the book "Java Foundation Classes in a Nutshell".
* Written by David Flanagan. Copyright (c) 1999 by O"Reilly & Associates.  
* You may distribute this source code for non-commercial purposes only.
* You may study, modify, and use this example for any purpose, as long as
* this notice is retained.  Note that this example is provided "as is",
* WITHOUT WARRANTY of any kind either expressed or implied.
*/

import java.awt.*; import java.awt.event.*; import javax.swing.*; public class MenuDemo1 {

 public static void main(String[] args) {
   // Create a window for this demo
   JFrame frame = new JFrame("Menu Demo");
   JPanel panel = new JPanel();
   frame.getContentPane().add(panel, "Center");
   // Create an action listener for the menu items we will create
   // The MenuItemActionListener class is defined below
   ActionListener listener = new MenuItemActionListener(panel);
   // Create some menu panes, and fill them with menu items
   // The menuItem() method is important.  It is defined below.
   JMenu file = new JMenu("File");
   file.setMnemonic("F");
   file.add(menuItem("New", listener, "new", "N", KeyEvent.VK_N));
   file.add(menuItem("Open...", listener, "open", "O", KeyEvent.VK_O));
   file.add(menuItem("Save", listener, "save", "S", KeyEvent.VK_S));
   file.add(menuItem("Save As...", listener, "saveas", "A", KeyEvent.VK_A));
   JMenu edit = new JMenu("Edit");
   edit.setMnemonic("E");
   edit.add(menuItem("Cut", listener, "cut", 0, KeyEvent.VK_X));
   edit.add(menuItem("Copy", listener, "copy", "C", KeyEvent.VK_C));
   edit.add(menuItem("Paste", listener, "paste", 0, KeyEvent.VK_V));
   // Create a menubar and add these panes to it.
   JMenuBar menubar = new JMenuBar();
   menubar.add(file);
   menubar.add(edit);
   // Add menubar to the main window.  Note special method to add menubars
   frame.setJMenuBar(menubar); 
   // Now create a popup menu and add the some stuff to it
   final JPopupMenu popup = new JPopupMenu();
   popup.add(menuItem("Open...", listener, "open", 0, 0));
   popup.addSeparator();                // Add a separator between items
   JMenu colors = new JMenu("Colors");  // Create a submenu
   popup.add(colors);                   // and add it to the popup menu
   // Now fill the submenu with mutually-exclusive radio buttons
   ButtonGroup colorgroup = new ButtonGroup();
   colors.add(radioItem("Red", listener, "color(red)", colorgroup));
   colors.add(radioItem("Green", listener, "color(green)", colorgroup));
   colors.add(radioItem("Blue", listener, "color(blue)", colorgroup));
   // Arrange to display the popup menu when the user clicks in the window
   panel.addMouseListener(new MouseAdapter() {
     public void mousePressed(MouseEvent e) {
 // Check whether this is the right type of event to pop up a popup
 // menu on this platform.  Usually checks for right button down.
 if (e.isPopupTrigger()) 
   popup.show((Component)e.getSource(), e.getX(), e.getY());
     }
   });
   // Finally, make our main window appear
   frame.setSize(450, 300);
   frame.setVisible(true);
 }
 // A convenience method for creating menu items.
 public static JMenuItem menuItem(String label, 
          ActionListener listener, String command, 
          int mnemonic, int acceleratorKey) {
   JMenuItem item = new JMenuItem(label);
   item.addActionListener(listener);
   item.setActionCommand(command);
   if (mnemonic != 0) item.setMnemonic((char) mnemonic);
   if (acceleratorKey != 0) 
     item.setAccelerator(KeyStroke.getKeyStroke(acceleratorKey, 
            java.awt.Event.CTRL_MASK));
   return item;
 }
 // A convenience method for creating radio button menu items.
 public static JMenuItem radioItem(String label, ActionListener listener, 
           String command, ButtonGroup mutExGroup) {
   JMenuItem item = new JRadioButtonMenuItem(label);
   item.addActionListener(listener);
   item.setActionCommand(command);
   mutExGroup.add(item);
   return item;
 }
 // A event listener class used with the menu items created above.
 // For this demo, it just displays a dialog box when an item is selected.
 public static class MenuItemActionListener implements ActionListener {
   Component parent;
   public MenuItemActionListener(Component parent) { this.parent = parent; }
   public void actionPerformed(ActionEvent e) {
     JMenuItem item = (JMenuItem) e.getSource();
     String cmd = item.getActionCommand();
     JOptionPane.showMessageDialog(parent, cmd + " was selected.");
   }
 }

}



 </source>
   
  
 
  



Menu Demo 4

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Button; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; public class MediumPopupMenuSample {

 public static void main(String args[]) {
   // Define ActionListener
   ActionListener aListener = new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       System.out.println("Selected: " + event.getActionCommand());
     }
   };
   // Define PopupMenuListener
   PopupMenuListener pListener = new PopupMenuListener() {
     public void popupMenuCanceled(PopupMenuEvent event) {
       System.out.println("Canceled");
     }
     public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
       System.out.println("Becoming Invisible");
     }
     public void popupMenuWillBecomeVisible(PopupMenuEvent event) {
       System.out.println("Becoming Visible");
     }
   };
   // Define
   JFrame frame = new JFrame("Popup Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPopupMenu.setDefaultLightWeightPopupEnabled(false);
   // Create popup menu, attach popup menu listener
   final JPopupMenu popupMenu = new JPopupMenu();
   popupMenu.addPopupMenuListener(pListener);
   // Cut
   JMenuItem cutItem = new JMenuItem("Cut");
   cutItem.addActionListener(aListener);
   popupMenu.add(cutItem);
   // Copy
   JMenuItem copyItem = new JMenuItem("Copy");
   copyItem.addActionListener(aListener);
   popupMenu.add(copyItem);
   // Paste
   JMenuItem pasteItem = new JMenuItem("Paste");
   pasteItem.addActionListener(aListener);
   pasteItem.setEnabled(false);
   popupMenu.add(pasteItem);
   // Separator
   popupMenu.addSeparator();
   // Find
   JMenuItem findItem = new JMenuItem("Find");
   findItem.addActionListener(aListener);
   popupMenu.add(findItem);
   // Enable showing
   MouseListener mouseListener = new JPopupMenuShower(popupMenu);
   frame.addMouseListener(mouseListener);
   Button button = new Button("Label");
   button.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.out.println(popupMenu.isLightWeightPopupEnabled());
     }
   });
   frame.getContentPane().add(button, BorderLayout.SOUTH);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class JPopupMenuShower extends MouseAdapter {

 private JPopupMenu popup;
 public JPopupMenuShower(JPopupMenu popup) {
   this.popup = popup;
 }
 private void showIfPopupTrigger(MouseEvent mouseEvent) {
   if (popup.isPopupTrigger(mouseEvent)) {
     popup.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent
         .getY());
   }
 }
 public void mousePressed(MouseEvent mouseEvent) {
   showIfPopupTrigger(mouseEvent);
 }
 public void mouseReleased(MouseEvent mouseEvent) {
   showIfPopupTrigger(mouseEvent);
 }

}


 </source>
   
  
 
  



Menu Glue Demo

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; /**

* @author ges
* @author kwalrath
*/

/* MenuGlueDemo.java is a 1.4 application that requires no other files. */ public class MenuGlueDemo {

 public JMenuBar createMenuBar() {
   JMenuBar menuBar = new JMenuBar();
   menuBar.add(createMenu("Menu 1"));
   menuBar.add(createMenu("Menu 2"));
   menuBar.add(Box.createHorizontalGlue());
   menuBar.add(createMenu("Menu 3"));
   return menuBar;
 }
 public JMenu createMenu(String title) {
   JMenu m = new JMenu(title);
   m.add("Menu item #1 in " + title);
   m.add("Menu item #2 in " + title);
   m.add("Menu item #3 in " + title);
   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() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("MenuGlueDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   MenuGlueDemo demo = new MenuGlueDemo();
   frame.setContentPane(demo.createMenuBar());
   //Display the window.
   frame.setSize(300, 100);
   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>
   
  
 
  



Menu item that can be selected or deselected

   <source lang="java">
 

import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.BorderFactory; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.border.EtchedBorder; public class CheckMenuItem {

 public static void main(String[] args) {
   final JLabel statusbar = new JLabel(" Statusbar");
   JMenuBar menubar = new JMenuBar();
   JMenu file = new JMenu("File");
   file.setMnemonic(KeyEvent.VK_F);
   JMenu view = new JMenu("View");
   view.setMnemonic(KeyEvent.VK_V);
   JCheckBoxMenuItem sbar = new JCheckBoxMenuItem("Show StatuBar");
   sbar.setState(true);
   sbar.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       if (statusbar.isVisible()) {
         statusbar.setVisible(false);
       } else {
         statusbar.setVisible(true);
       }
     }
   });
   view.add(sbar);
   menubar.add(file);
   menubar.add(view);
   JFrame f = new JFrame();
   f.setJMenuBar(menubar);
   statusbar.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
   f.add(statusbar, BorderLayout.SOUTH);
   f.setSize(360, 250);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Menu Layout Demo

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

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 is a 1.4 application that 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() {
       //Make sure we have nice window decorations.
       JFrame.setDefaultLookAndFeelDecorated(true);
       //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>
   
  
 
  



Menu Look Demo, except the menu items actually do

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; 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; /*

* This class is just like MenuLookDemo, except the menu items actually do
* something, thanks to event listeners.
*/

public class MenuDemo implements ActionListener, ItemListener {

 JTextArea output;
 JScrollPane scrollPane;
 String newline = "\n";
 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");
   menuItem.addActionListener(this);
   menu.add(menuItem);
   ImageIcon icon = createImageIcon("images/1.gif");
   menuItem = new JMenuItem("Both text and icon", icon);
   menuItem.setMnemonic(KeyEvent.VK_B);
   menuItem.addActionListener(this);
   menu.add(menuItem);
   menuItem = new JMenuItem(icon);
   menuItem.setMnemonic(KeyEvent.VK_D);
   menuItem.addActionListener(this);
   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);
   rbMenuItem.addActionListener(this);
   menu.add(rbMenuItem);
   rbMenuItem = new JRadioButtonMenuItem("Another one");
   rbMenuItem.setMnemonic(KeyEvent.VK_O);
   group.add(rbMenuItem);
   rbMenuItem.addActionListener(this);
   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);
   cbMenuItem.addItemListener(this);
   menu.add(cbMenuItem);
   cbMenuItem = new JCheckBoxMenuItem("Another one");
   cbMenuItem.setMnemonic(KeyEvent.VK_H);
   cbMenuItem.addItemListener(this);
   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));
   menuItem.addActionListener(this);
   submenu.add(menuItem);
   menuItem = new JMenuItem("Another item");
   menuItem.addActionListener(this);
   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;
 }
 public void actionPerformed(ActionEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Action event detected." + newline + "    Event source: "
       + source.getText() + " (an instance of " + getClassName(source)
       + ")";
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 public void itemStateChanged(ItemEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Item event detected."
       + newline
       + "    Event source: "
       + source.getText()
       + " (an instance of "
       + getClassName(source)
       + ")"
       + newline
       + "    New state: "
       + ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
           : "unselected");
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 // Returns just the class name -- no package info.
 protected String getClassName(Object o) {
   String classString = o.getClass().getName();
   int dotIndex = classString.lastIndexOf(".");
   return classString.substring(dotIndex + 1);
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path) {
   java.net.URL imgURL = MenuDemo.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() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("MenuDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   MenuDemo demo = new MenuDemo();
   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>
   
  
 
  



Menu Sample 3

   <source lang="java">
 

import java.awt.event.KeyEvent; import javax.swing.Box; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; public class MenuSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Menu Glue Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu fileMenu = new JMenu("File");
   fileMenu.setMnemonic(KeyEvent.VK_F);
   bar.add(fileMenu);
   // Edit Menu, E - Mnemonic
   JMenu editMenu = new JMenu("Edit");
   editMenu.setMnemonic(KeyEvent.VK_E);
   bar.add(editMenu);
   // Move help menu to right side
   bar.add(Box.createHorizontalGlue());
   // Help Menu, H - Mnemonic
   JMenu helpMenu = new JMenu("Help");
   helpMenu.setMnemonic(KeyEvent.VK_H);
   bar.add(helpMenu);
   frame.setJMenuBar(bar);
   frame.setSize(300, 150);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Menu Selection Manager Demo

   <source lang="java">
 

/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*

* Copyright (c) 2006 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:
*
* -Redistribution of source code must retain the above copyright notice, this
*  list of conditions and the following disclaimer.
*
* -Redistribution 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, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/

import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; 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; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.Timer; /*

* MenuSelectionManagerDemo.java is a 1.4 application that requires
* images/middle.gif.
*/

/*

* This class is just like MenuDemo, except every second (thanks to a Timer) the
* selected path of the menu is printed in the text area.
*/

public class MenuSelectionManagerDemo implements ActionListener, ItemListener {

 JTextArea output;
 JScrollPane scrollPane;
 String newline = "\n";
 public final static int ONE_SECOND = 1000;
 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");
   menuItem.addActionListener(this);
   menu.add(menuItem);
   ImageIcon icon = createImageIcon("1.gif");
   menuItem = new JMenuItem("Both text and icon", icon);
   menuItem.setMnemonic(KeyEvent.VK_B);
   menuItem.addActionListener(this);
   menu.add(menuItem);
   menuItem = new JMenuItem(icon);
   menuItem.setMnemonic(KeyEvent.VK_D);
   menuItem.addActionListener(this);
   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);
   rbMenuItem.addActionListener(this);
   menu.add(rbMenuItem);
   rbMenuItem = new JRadioButtonMenuItem("Another one");
   rbMenuItem.setMnemonic(KeyEvent.VK_O);
   group.add(rbMenuItem);
   rbMenuItem.addActionListener(this);
   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);
   cbMenuItem.addItemListener(this);
   menu.add(cbMenuItem);
   cbMenuItem = new JCheckBoxMenuItem("Another one");
   cbMenuItem.setMnemonic(KeyEvent.VK_H);
   cbMenuItem.addItemListener(this);
   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));
   menuItem.addActionListener(this);
   submenu.add(menuItem);
   menuItem = new JMenuItem("Another item");
   menuItem.addActionListener(this);
   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);
   Timer timer = new Timer(ONE_SECOND, new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
       MenuElement[] path = MenuSelectionManager.defaultManager()
           .getSelectedPath();
       for (int i = 0; i < path.length; i++) {
         if (path[i].getComponent() instanceof javax.swing.JMenuItem) {
           JMenuItem mi = (JMenuItem) path[i].getComponent();
           if ("".equals(mi.getText())) {
             output.append("ICON-ONLY MENU ITEM > ");
           } else {
             output.append(mi.getText() + " > ");
           }
         }
       }
       if (path.length > 0)
         output.append(newline);
     }
   });
   timer.start();
   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;
 }
 public void actionPerformed(ActionEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Action event detected." + newline + "    Event source: "
       + source.getText() + " (an instance of " + getClassName(source)
       + ")";
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 public void itemStateChanged(ItemEvent e) {
   JMenuItem source = (JMenuItem) (e.getSource());
   String s = "Item event detected."
       + newline
       + "    Event source: "
       + source.getText()
       + " (an instance of "
       + getClassName(source)
       + ")"
       + newline
       + "    New state: "
       + ((e.getStateChange() == ItemEvent.SELECTED) ? "selected"
           : "unselected");
   output.append(s + newline);
   output.setCaretPosition(output.getDocument().getLength());
 }
 // Returns just the class name -- no package info.
 protected String getClassName(Object o) {
   String classString = o.getClass().getName();
   int dotIndex = classString.lastIndexOf(".");
   return classString.substring(dotIndex + 1);
 }
 /** Returns an ImageIcon, or null if the path was invalid. */
 protected static ImageIcon createImageIcon(String path) {
   java.net.URL imgURL = MenuSelectionManagerDemo.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() {
   //Make sure we have nice window decorations.
   JFrame.setDefaultLookAndFeelDecorated(true);
   //Create and set up the window.
   JFrame frame = new JFrame("MenuSelectionManagerDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   //Create and set up the content pane.
   MenuSelectionManagerDemo demo = new MenuSelectionManagerDemo();
   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>
   
  
 
  



Menu X

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.Event; import java.awt.GridLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.Icon; 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.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuKeyEvent; import javax.swing.event.MenuKeyListener; import javax.swing.event.MenuListener; public class MenuX {

 static class MenuActionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     System.out.println("Selected: " + e.getActionCommand());
   }
 }
 static class MyMenuListener implements MenuListener {
   public void menuCanceled(MenuEvent e) {
     System.out.println("Canceled");
   }
   public void menuDeselected(MenuEvent e) {
     System.out.println("Deselected");
   }
   public void menuSelected(MenuEvent e) {
     System.out.println("Selected");
   }
 }
 static class MyChangeListener implements ChangeListener {
   public void stateChanged(ChangeEvent event) {
     Object source = event.getSource();
     if (source instanceof AbstractButton) {
       AbstractButton aButton = (AbstractButton) source;
       ButtonModel aModel = aButton.getModel();
       boolean armed = aModel.isArmed();
       boolean pressed = aModel.isPressed();
       boolean selected = aModel.isSelected();
       System.out.println("Changed " + aButton.getText() + ": "
           + armed + "/" + pressed + "/" + selected);
       /*
        * } else if (source instanceof MenuSelectionManager) {
        * MenuSelectionManager manager = (MenuSelectionManager)source;
        * MenuElement path[] = manager.getSelectedPath(); for (int i=0,
        * n=path.length; i <n; i++) { MenuElement item =
        * (MenuElement)path[i]; System.out.print ("-->" +
        * item.getClass().getName()); } System.out.println();
        */}
   }
 }
 static class MyMenuKeyListener implements MenuKeyListener {
   public void menuKeyPressed(MenuKeyEvent e) {
     printInfo("Pressed", e);
   }
   public void menuKeyReleased(MenuKeyEvent e) {
     printInfo("Released", e);
   }
   public void menuKeyTyped(MenuKeyEvent e) {
     printInfo("Typed", e);
   }
   private void printInfo(String eventType, MenuKeyEvent e) {
     System.out.print(eventType + ":");
     MenuElement path[] = e.getPath();
     /*
      * for (int i=0, n=path.length; i <n; i++) { MenuElement item =
      * (MenuElement)path[i]; System.out.print ("==>" +
      * item.getClass().getName()); }
      */System.out.println();
   }
 }
 public static void main(String args[]) {
   ActionListener actionListener = new MenuActionListener();
   MenuKeyListener menuKeyListener = new MyMenuKeyListener();
   ChangeListener cListener = new MyChangeListener();
   MenuListener menuListener = new MyMenuListener();
   MenuSelectionManager manager = MenuSelectionManager.defaultManager();
   manager.addChangeListener(cListener);
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new VerticalMenuBar();
   //    JMenuBar bar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu file = new JMenu("File");
   file.setMnemonic(KeyEvent.VK_F);
   file.addChangeListener(cListener);
   file.addMenuListener(menuListener);
   file.addMenuKeyListener(menuKeyListener);
   JPopupMenu popupMenu = file.getPopupMenu();
   popupMenu.setLayout(new GridLayout(3, 3));
   bar.add(file);
   // File->New, N - Mnemonic
   JMenuItem newItem = new JMenuItem("New", KeyEvent.VK_N);
   newItem.addActionListener(actionListener);
   newItem.addChangeListener(cListener);
   newItem.addMenuKeyListener(menuKeyListener);
   file.add(newItem);
   // File->Open, O - Mnemonic
   JMenuItem openItem = new JMenuItem("Open", KeyEvent.VK_O);
   openItem.addActionListener(actionListener);
   openItem.addChangeListener(cListener);
   openItem.addMenuKeyListener(menuKeyListener);
   file.add(openItem);
   // File->Close, C - Mnemonic
   JMenuItem closeItem = new JMenuItem("Close", KeyEvent.VK_C);
   closeItem.addActionListener(actionListener);
   closeItem.addChangeListener(cListener);
   closeItem.addMenuKeyListener(menuKeyListener);
   file.add(closeItem);
   // Separator
   file.addSeparator();
   // File->Save, S - Mnemonic
   JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
   saveItem.addActionListener(actionListener);
   saveItem.addChangeListener(cListener);
   saveItem.addMenuKeyListener(menuKeyListener);
   file.add(saveItem);
   // Separator
   file.addSeparator();
   // File->Exit, X - Mnemonic
   JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
   exitItem.addActionListener(actionListener);
   exitItem.addChangeListener(cListener);
   exitItem.addMenuKeyListener(menuKeyListener);
   file.add(exitItem);
   // Edit Menu, E - Mnemonic
   JMenu edit = new JMenu("Edit");
   edit.setMnemonic(KeyEvent.VK_E);
   edit.addChangeListener(cListener);
   edit.addMenuListener(menuListener);
   edit.addMenuKeyListener(menuKeyListener);
   bar.add(edit);
   // Edit->Cut, T - Mnemonic, CTRL-X - Accelerator
   JMenuItem cutItem = new JMenuItem("Cut", KeyEvent.VK_T);
   cutItem.addActionListener(actionListener);
   cutItem.addChangeListener(cListener);
   cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
       Event.CTRL_MASK));
   cutItem.addMenuKeyListener(menuKeyListener);
   edit.add(cutItem);
   // Edit->Copy, C - Mnemonic, CTRL-C - Accelerator
   JMenuItem copyItem = new JMenuItem("Copy", KeyEvent.VK_C);
   copyItem.addActionListener(actionListener);
   copyItem.addChangeListener(cListener);
   copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
       Event.CTRL_MASK));
   copyItem.addMenuKeyListener(menuKeyListener);
   copyItem.setEnabled(false);
   edit.add(copyItem);
   // Edit->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled
   JMenuItem pasteItem = new JMenuItem("Paste", KeyEvent.VK_P);
   pasteItem.addActionListener(actionListener);
   pasteItem.addChangeListener(cListener);
   pasteItem.addMenuKeyListener(menuKeyListener);
   pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
       Event.CTRL_MASK));
   pasteItem.setEnabled(false);
   edit.add(pasteItem);
   // Separator
   edit.addSeparator();
   // Edit->Find, F - Mnemonic, F3 - Accelerator
   JMenuItem findItem = new JMenuItem("Find", KeyEvent.VK_F);
   findItem.addActionListener(actionListener);
   findItem.addChangeListener(cListener);
   findItem.addMenuKeyListener(menuKeyListener);
   findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
   edit.add(findItem);
   // Edit->Options Submenu, O - Mnemonic, at.gif - Icon Image File
   JMenu findOptions = new JMenu("Options");
   findOptions.addChangeListener(cListener);
   findOptions.addMenuListener(menuListener);
   findOptions.addMenuKeyListener(menuKeyListener);
   Icon atIcon = new ImageIcon("at.gif");
   findOptions.setIcon(atIcon);
   findOptions.setMnemonic(KeyEvent.VK_O);
   // ButtonGrou for radio buttons
   ButtonGroup directionGroup = new ButtonGroup();
   // Edit->Options->Forward, F - Mnemonic, in group
   JRadioButtonMenuItem forward = new JRadioButtonMenuItem("Forward", true);
   forward.addActionListener(actionListener);
   forward.addChangeListener(cListener);
   forward.addMenuKeyListener(menuKeyListener);
   forward.setMnemonic(KeyEvent.VK_F);
   findOptions.add(forward);
   directionGroup.add(forward);
   // Edit->Options->Backward, B - Mnemonic, in group
   JRadioButtonMenuItem backward = new JRadioButtonMenuItem("Backward");
   backward.addActionListener(actionListener);
   backward.addChangeListener(cListener);
   backward.addMenuKeyListener(menuKeyListener);
   backward.setMnemonic(KeyEvent.VK_B);
   findOptions.add(backward);
   directionGroup.add(backward);
   // Separator
   findOptions.addSeparator();
   // Edit->Options->Case Sensitive, C - Mnemonic
   JCheckBoxMenuItem caseItem = new JCheckBoxMenuItem("Case Sensitive");
   caseItem.addActionListener(actionListener);
   caseItem.addChangeListener(cListener);
   caseItem.addMenuKeyListener(menuKeyListener);
   caseItem.setMnemonic(KeyEvent.VK_C);
   findOptions.add(caseItem);
   edit.add(findOptions);
   frame.setJMenuBar(bar);
   //    frame.getContentPane().add(bar, BorderLayout.EAST);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class VerticalMenuBar extends JMenuBar {

 private static final LayoutManager grid = new GridLayout(0, 1);
 public VerticalMenuBar() {
   setLayout(grid);
 }

}



 </source>
   
  
 
  



Menu Y

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.Event; import java.awt.GridLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.Icon; 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.JPopupMenu; import javax.swing.JRadioButtonMenuItem; import javax.swing.KeyStroke; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.MenuEvent; import javax.swing.event.MenuKeyEvent; import javax.swing.event.MenuKeyListener; import javax.swing.event.MenuListener; public class MenuY {

 static class MenuActionListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     System.out.println("Selected: " + e.getActionCommand());
   }
 }
 static class MyMenuListener implements MenuListener {
   public void menuCanceled(MenuEvent e) {
     System.out.println("Canceled");
   }
   public void menuDeselected(MenuEvent e) {
     System.out.println("Deselected");
   }
   public void menuSelected(MenuEvent e) {
     System.out.println("Selected");
   }
 }
 static class MyChangeListener implements ChangeListener {
   public void stateChanged(ChangeEvent event) {
     Object source = event.getSource();
     if (source instanceof AbstractButton) {
       AbstractButton aButton = (AbstractButton) source;
       ButtonModel aModel = aButton.getModel();
       boolean armed = aModel.isArmed();
       boolean pressed = aModel.isPressed();
       boolean selected = aModel.isSelected();
       System.out.println("Changed " + aButton.getText() + ": "
           + armed + "/" + pressed + "/" + selected);
       /*
        * } else if (source instanceof MenuSelectionManager) {
        * MenuSelectionManager manager = (MenuSelectionManager)source;
        * MenuElement path[] = manager.getSelectedPath(); for (int i=0,
        * n=path.length; i <n; i++) { MenuElement item =
        * (MenuElement)path[i]; System.out.print ("-->" +
        * item.getClass().getName()); } System.out.println();
        */}
   }
 }
 static class MyMenuKeyListener implements MenuKeyListener {
   public void menuKeyPressed(MenuKeyEvent e) {
     printInfo("Pressed", e);
   }
   public void menuKeyReleased(MenuKeyEvent e) {
     printInfo("Released", e);
   }
   public void menuKeyTyped(MenuKeyEvent e) {
     printInfo("Typed", e);
   }
   private void printInfo(String eventType, MenuKeyEvent e) {
     System.out.print(eventType + ":");
     MenuElement path[] = e.getPath();
     /*
      * for (int i=0, n=path.length; i <n; i++) { MenuElement item =
      * (MenuElement)path[i]; System.out.print ("==>" +
      * item.getClass().getName()); }
      */System.out.println();
   }
 }
 public static void main(String args[]) {
   ActionListener actionListener = new MenuActionListener();
   MenuKeyListener menuKeyListener = new MyMenuKeyListener();
   ChangeListener cListener = new MyChangeListener();
   MenuListener menuListener = new MyMenuListener();
   MenuSelectionManager manager = MenuSelectionManager.defaultManager();
   manager.addChangeListener(cListener);
   JFrame frame = new JFrame("MenuSample Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new VerticalMenuBar();
   //    JMenuBar bar = new JMenuBar();
   // File Menu, F - Mnemonic
   JMenu file = new JMenu("File");
   file.setMnemonic(KeyEvent.VK_F);
   file.addChangeListener(cListener);
   file.addMenuListener(menuListener);
   file.addMenuKeyListener(menuKeyListener);
   JPopupMenu popupMenu = file.getPopupMenu();
   popupMenu.setLayout(new GridLayout(3, 3));
   bar.add(file);
   // File->New, N - Mnemonic
   JMenuItem newItem = new JMenuItem("New", KeyEvent.VK_N);
   newItem.addActionListener(actionListener);
   newItem.addChangeListener(cListener);
   newItem.addMenuKeyListener(menuKeyListener);
   file.add(newItem);
   // File->Open, O - Mnemonic
   JMenuItem openItem = new JMenuItem("Open", KeyEvent.VK_O);
   openItem.addActionListener(actionListener);
   openItem.addChangeListener(cListener);
   openItem.addMenuKeyListener(menuKeyListener);
   file.add(openItem);
   // File->Close, C - Mnemonic
   JMenuItem closeItem = new JMenuItem("Close", KeyEvent.VK_C);
   closeItem.addActionListener(actionListener);
   closeItem.addChangeListener(cListener);
   closeItem.addMenuKeyListener(menuKeyListener);
   file.add(closeItem);
   // Separator
   file.addSeparator();
   // File->Save, S - Mnemonic
   JMenuItem saveItem = new JMenuItem("Save", KeyEvent.VK_S);
   saveItem.addActionListener(actionListener);
   saveItem.addChangeListener(cListener);
   saveItem.addMenuKeyListener(menuKeyListener);
   file.add(saveItem);
   // Separator
   file.addSeparator();
   // File->Exit, X - Mnemonic
   JMenuItem exitItem = new JMenuItem("Exit", KeyEvent.VK_X);
   exitItem.addActionListener(actionListener);
   exitItem.addChangeListener(cListener);
   exitItem.addMenuKeyListener(menuKeyListener);
   file.add(exitItem);
   // Edit Menu, E - Mnemonic
   JMenu edit = new JMenu("Edit");
   edit.setMnemonic(KeyEvent.VK_E);
   edit.addChangeListener(cListener);
   edit.addMenuListener(menuListener);
   edit.addMenuKeyListener(menuKeyListener);
   bar.add(edit);
   // Edit->Cut, T - Mnemonic, CTRL-X - Accelerator
   JMenuItem cutItem = new JMenuItem("Cut", KeyEvent.VK_T);
   cutItem.addActionListener(actionListener);
   cutItem.addChangeListener(cListener);
   cutItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X,
       Event.CTRL_MASK));
   cutItem.addMenuKeyListener(menuKeyListener);
   edit.add(cutItem);
   // Edit->Copy, C - Mnemonic, CTRL-C - Accelerator
   JMenuItem copyItem = new JMenuItem("Copy", KeyEvent.VK_C);
   copyItem.addActionListener(actionListener);
   copyItem.addChangeListener(cListener);
   copyItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C,
       Event.CTRL_MASK));
   copyItem.addMenuKeyListener(menuKeyListener);
   copyItem.setEnabled(false);
   edit.add(copyItem);
   // Edit->Paste, P - Mnemonic, CTRL-V - Accelerator, Disabled
   JMenuItem pasteItem = new JMenuItem("Paste", KeyEvent.VK_P);
   pasteItem.addActionListener(actionListener);
   pasteItem.addChangeListener(cListener);
   pasteItem.addMenuKeyListener(menuKeyListener);
   pasteItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V,
       Event.CTRL_MASK));
   pasteItem.setEnabled(false);
   edit.add(pasteItem);
   // Separator
   edit.addSeparator();
   // Edit->Find, F - Mnemonic, F3 - Accelerator
   JMenuItem findItem = new JMenuItem("Find", KeyEvent.VK_F);
   findItem.addActionListener(actionListener);
   findItem.addChangeListener(cListener);
   findItem.addMenuKeyListener(menuKeyListener);
   findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
   edit.add(findItem);
   // Edit->Options Submenu, O - Mnemonic, at.gif - Icon Image File
   Icon atIcon = new ImageIcon("at.gif");
   Action findAction = new AbstractAction("Options", atIcon) {
     ActionListener actionListener = new MenuActionListener();
     public void actionPerformed(ActionEvent e) {
       actionListener.actionPerformed(e);
     }
   };
   findAction.putValue(Action.MNEMONIC_KEY, new Integer(KeyEvent.VK_O));
   JMenuItem jMenuItem = new JMenuItem(findAction);
   JMenu findOptions = new JMenu(findAction);
   findOptions.addChangeListener(cListener);
   findOptions.addMenuListener(menuListener);
   findOptions.addMenuKeyListener(menuKeyListener);
   // ButtonGrou for radio buttons
   ButtonGroup directionGroup = new ButtonGroup();
   // Edit->Options->Forward, F - Mnemonic, in group
   JRadioButtonMenuItem forward = new JRadioButtonMenuItem("Forward", true);
   forward.addActionListener(actionListener);
   forward.addChangeListener(cListener);
   forward.addMenuKeyListener(menuKeyListener);
   forward.setMnemonic(KeyEvent.VK_F);
   findOptions.add(forward);
   directionGroup.add(forward);
   // Edit->Options->Backward, B - Mnemonic, in group
   JRadioButtonMenuItem backward = new JRadioButtonMenuItem("Backward");
   backward.addActionListener(actionListener);
   backward.addChangeListener(cListener);
   backward.addMenuKeyListener(menuKeyListener);
   backward.setMnemonic(KeyEvent.VK_B);
   findOptions.add(backward);
   directionGroup.add(backward);
   // Separator
   findOptions.addSeparator();
   // Edit->Options->Case Sensitive, C - Mnemonic
   JCheckBoxMenuItem caseItem = new JCheckBoxMenuItem("Case Sensitive");
   caseItem.addActionListener(actionListener);
   caseItem.addChangeListener(cListener);
   caseItem.addMenuKeyListener(menuKeyListener);
   caseItem.setMnemonic(KeyEvent.VK_C);
   findOptions.add(caseItem);
   edit.add(findOptions);
   frame.setJMenuBar(bar);
   //    frame.getContentPane().add(bar, BorderLayout.EAST);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class VerticalMenuBar extends JMenuBar {

 private static final LayoutManager grid = new GridLayout(0, 1);
 public VerticalMenuBar() {
   setLayout(grid);
 }

}



 </source>
   
  
 
  



Place commands that hide/show various toolbars

   <source lang="java">
 

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.KeyStroke; public class Submenu {

 public static void main(String[] args) {
   JFrame f = new JFrame();
   JMenuBar menubar = new JMenuBar();
   ImageIcon iconNew = new ImageIcon("new.png");
   ImageIcon iconOpen = new ImageIcon("open.png");
   ImageIcon iconSave = new ImageIcon("save.png");
   ImageIcon iconClose = new ImageIcon("exit.png");
   JMenu file = new JMenu("File");
   JMenu imp = new JMenu("Import");
   JMenuItem fileNew = new JMenuItem("New", iconNew);
   JMenuItem fileOpen = new JMenuItem("Open", iconOpen);
   JMenuItem fileSave = new JMenuItem("Save", iconSave);
   JMenuItem fileClose = new JMenuItem("Close", iconClose);
   file.setMnemonic(KeyEvent.VK_F);
   imp.setMnemonic(KeyEvent.VK_M);
   JMenuItem newsf = new JMenuItem("Import newsfeed list...");
   JMenuItem bookm = new JMenuItem("Import bookmarks...");
   JMenuItem mail = new JMenuItem("Import mail...");
   imp.add(newsf);
   imp.add(bookm);
   imp.add(mail);
   fileNew.setMnemonic(KeyEvent.VK_N);
   fileNew.setMnemonic(KeyEvent.VK_O);
   fileSave.setMnemonic(KeyEvent.VK_S);
   fileClose.setMnemonic(KeyEvent.VK_C);
   fileClose.setToolTipText("Exit application");
   fileClose.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
   fileClose.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       System.exit(0);
     }
   });
   file.add(fileNew);
   file.add(fileOpen);
   file.add(fileSave);
   file.addSeparator();
   file.add(imp);
   file.addSeparator();
   file.add(fileClose);
   menubar.add(file);
   f.setJMenuBar(menubar);
   f.setSize(360, 250);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



PopupMenu and Mouse Event

   <source lang="java">
 

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; public class PopupSample {

 public static void main(String args[]) {
   ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       System.out.println("Selected: "
           + actionEvent.getActionCommand());
     }
   };
   PopupMenuListener popupMenuListener = new PopupMenuListener() {
     public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
       System.out.println("Canceled");
     }
     public void popupMenuWillBecomeInvisible(
         PopupMenuEvent popupMenuEvent) {
       System.out.println("Becoming Invisible");
     }
     public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
       System.out.println("Becoming Visible");
     }
   };
   JFrame frame = new JFrame("Popup Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JPopupMenu popupMenu = new JPopupMenu();
   popupMenu.addPopupMenuListener(popupMenuListener);
   JMenuItem cutMenuItem = new JMenuItem("Cut");
   cutMenuItem.addActionListener(actionListener);
   popupMenu.add(cutMenuItem);
   JMenuItem copyMenuItem = new JMenuItem("Copy");
   copyMenuItem.addActionListener(actionListener);
   popupMenu.add(copyMenuItem);
   JMenuItem pasteMenuItem = new JMenuItem("Paste");
   pasteMenuItem.addActionListener(actionListener);
   pasteMenuItem.setEnabled(false);
   popupMenu.add(pasteMenuItem);
   popupMenu.addSeparator();
   JMenuItem findMenuItem = new JMenuItem("Find");
   findMenuItem.addActionListener(actionListener);
   popupMenu.add(findMenuItem);
   MouseListener mouseListener = new JPopupMenuShower(popupMenu);
   frame.addMouseListener(mouseListener);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class JPopupMenuShower extends MouseAdapter {

 private JPopupMenu popup;
 public JPopupMenuShower(JPopupMenu popup) {
   this.popup = popup;
 }
 private void showIfPopupTrigger(MouseEvent mouseEvent) {
   if (popup.isPopupTrigger(mouseEvent)) {
     popup.show(mouseEvent.getComponent(), mouseEvent.getX(), mouseEvent
         .getY());
   }
 }
 public void mousePressed(MouseEvent mouseEvent) {
   showIfPopupTrigger(mouseEvent);
 }
 public void mouseReleased(MouseEvent mouseEvent) {
   showIfPopupTrigger(mouseEvent);
 }

}



 </source>
   
  
 
  



Popup Menu Demo

   <source lang="java">
 

//From: mg@dsd.camb.inmet.ru (Mitch Gart) import java.awt.BorderLayout; import java.awt.Button; import java.awt.ruponent; import java.awt.Frame; import java.awt.Label; import java.awt.Menu; import java.awt.MenuBar; import java.awt.MenuItem; import java.awt.Panel; import java.awt.PopupMenu; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.Hashtable; public class PopupDemo extends Frame implements ActionListener, MouseListener {

 public static void main(String argv[]) {
   new PopupDemo().setVisible(true);
 }
 public PopupDemo() {
   MenuBar mb = new MenuBar();
   setMenuBar(mb);
   Menu m = new Menu("file");
   mb.add(m);
   MenuItem item = new MenuItem("file-1");
   item.addActionListener(this);
   m.add(item);
   item = new MenuItem("file-2");
   m.add(item);
   setSize(100, 100);
   setLayout(new BorderLayout());
   Label l = new Label("label");
   addPopup(l, "label");
   add(l, "North");
   Panel p = new Panel();
   addPopup(p, "Panel");
   add(p, "Center");
   Button b = new Button("button");
   addPopup(b, "button");
   add(b, "South");
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("actionPerformed, event=" + e + ", mod="
       + getMods(e));
   System.out.println(" command=" + e.getActionCommand());
   System.out.println(" param=" + e.paramString());
   System.out.println(" source=" + e.getSource());
 }
 String getMods(ActionEvent e) {
   return getMods(e.getModifiers());
 }
 String getMods(MouseEvent e) {
   return getMods(e.getModifiers());
 }
 // a convenience routine for printing the Modifier keys
 String getMods(int mods) {
   String modstr = "";
   if ((mods & ActionEvent.SHIFT_MASK) == ActionEvent.SHIFT_MASK)
     modstr += (" SHIFT");
   if ((mods & ActionEvent.ALT_MASK) == ActionEvent.ALT_MASK)
     modstr += (" ALT");
   if ((mods & ActionEvent.CTRL_MASK) == ActionEvent.CTRL_MASK)
     modstr += (" CTRL");
   if ((mods & ActionEvent.META_MASK) == ActionEvent.META_MASK)
     modstr += (" META");
   return modstr;
 }
 public void mouseClicked(MouseEvent e) {
   mouseAction("mouseClicked", e);
 }
 public void mouseEntered(MouseEvent e) {
 }
 public void mouseExited(MouseEvent e) {
 }
 public void mousePressed(MouseEvent e) {
   mouseAction("mousePressed", e);
 }
 public void mouseReleased(MouseEvent e) {
   mouseAction("mouseReleased", e);
 }
 void mouseAction(String which, MouseEvent e) {
   Component c = e.getComponent();
   System.out.println(which + "e=" + e + ", mods=" + getMods(e)
       + ", component=" + c);
   if (e.isPopupTrigger()) {
     System.out.println("isPopup");
     PopupMenu pm = getHash(c);
     pm.show(c, c.getSize().width / 2, c.getSize().height / 2);
   }
 }
 void addPopup(Component c, String name) {
   PopupMenu pm = new PopupMenu();
   MenuItem mi = new MenuItem(name + "-1");
   mi.addActionListener(this);
   pm.add(mi);
   mi = new MenuItem(name + "-2");
   pm.add(mi);
   setHash(c, pm);
   c.add(pm);
   c.addMouseListener(this);
 }
 Hashtable popupTable = new Hashtable();
 void setHash(Component c, PopupMenu p) {
   popupTable.put(c, p);
 }
 PopupMenu getHash(Component c) {
   return (PopupMenu) (popupTable.get(c));
 }

}


 </source>
   
  
 
  



PopupMenu Sample

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTextField; import javax.swing.KeyStroke; import javax.swing.text.BadLocationException; public class PopupMenuSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Popup Example");
   Container content = frame.getContentPane();
   final JPopupMenu popup = new JPopupMenu();
   JMenuItem menuItem1 = new JMenuItem("Option 1");
   popup.add(menuItem1);
   JMenuItem menuItem2 = new JMenuItem("Option 2");
   popup.add(menuItem2);
   final JTextField textField = new JTextField();
   content.add(textField, BorderLayout.NORTH);
   ActionListener actionListener = new ActionListener() {
     public void actionPerformed(ActionEvent actionEvent) {
       try {
         int dotPosition = textField.getCaretPosition();
         Rectangle popupLocation = textField
             .modelToView(dotPosition);
         popup.show(textField, popupLocation.x, popupLocation.y);
       } catch (BadLocationException badLocationException) {
         System.out.println("Oops");
       }
     }
   };
   KeyStroke keystroke = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, 0,
       false);
   textField.registerKeyboardAction(actionListener, keystroke,
       JComponent.WHEN_FOCUSED);
   frame.setSize(250, 150);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Provide a pop-up menu using a Frame

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

import java.awt.AWTEvent; import java.awt.ruponent; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Frame; import java.awt.MenuItem; import java.awt.PopupMenu; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; /**

* Provide a pop-up menu using a Frame. On most platforms, changing the mouse
* "settings" changes how the isPopupTrigger() method behaves instantly - which
* is as it should be!
*/

public class PopupDemo extends Frame {

 /** "main" method - for testing. */
 public static void main(String[] av) {
   new PopupDemo("Hello").setVisible(true);
 }
 /** Construct the main program */
 public PopupDemo(String title) {
   super(title);
   setLayout(new FlowLayout());
   add(new PopupContainer("Hello, and welcome to the world of Java"));
   pack();
   setVisible(true);
 }

} /*

* A component to demonstrate use of PopupMenu. The user has to ask for the menu
* to popup in Java"s platform-dependant way (e.g., right mouse click on X
* Windows, MS-Windows).
* 
* Alternately, you could watch for keypress events and provide your own
* platform-independant keyboard popup menu character such as M for Menu (not
* CTRL/M; Mac"s don"t have a CTRL key).
*/

class PopupContainer extends Component {

 PopupMenu m;
 PopupContainer(String s) {
   m = new PopupMenu(s);
   m.add(new MenuItem("Open"));
   m.add(new MenuItem("Close"));
   MenuItem qB;
   m.add(qB = new MenuItem("Exit"));
   class Quitter implements ActionListener {
     public void actionPerformed(ActionEvent e) {
       System.exit(0);
     }
   }
   qB.addActionListener(new Quitter());
   add(m); // add Popup to Component
   enableEvents(AWTEvent.MOUSE_EVENT_MASK);
 }
 public void processMouseEvent(MouseEvent me) {
   System.err.println("MouseEvent: " + me);
   if (me.isPopupTrigger())
     m.show(this, me.getX(), me.getY());
   else
     super.processMouseEvent(me);
 };
 /** Compute our minimum size */
 public Dimension getMinimumSize() {
   return new Dimension(200, 200);
 }
 final int PREF_PAD = 10;
 /** Computer our best size */
 public Dimension getPreferredSize() {
   Dimension d = getMinimumSize();
   return new Dimension(d.width + PREF_PAD, d.height + PREF_PAD);
 }
 /** Computer our maximum allowed size */
 public Dimension getMaximumSize() {
   Dimension d = getMinimumSize();
   return new Dimension(d.width * 2, d.height * 2);
 }

}



 </source>
   
  
 
  



RadioButton Menu Sample

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.event.KeyEvent; import javax.swing.ButtonGroup; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JRadioButtonMenuItem; public class RadioButtonMenuSample {

 public static void main(String args[]) {
   JFrame f = new JFrame("JRadioButtonMenuItem Sample");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new JMenuBar();
   JMenu menu = new JMenu("Options");
   menu.setMnemonic(KeyEvent.VK_O);
   ButtonGroup group = new ButtonGroup();
   JRadioButtonMenuItem menuItem = new JRadioButtonMenuItem("North");
   group.add(menuItem);
   menu.add(menuItem);
   menuItem = new JRadioButtonMenuItem("East");
   group.add(menuItem);
   menu.add(menuItem);
   menuItem = new JRadioButtonMenuItem("West");
   group.add(menuItem);
   menu.add(menuItem);
   menuItem = new JRadioButtonMenuItem("South");
   group.add(menuItem);
   menu.add(menuItem);
   menuItem = new JRadioButtonMenuItem("Center");
   group.add(menuItem);
   menu.add(menuItem);
   bar.add(menu);
   f.setJMenuBar(bar);
   f.setSize(300, 200);
   f.setVisible(true);
 }

}


 </source>
   
  
 
  



Radio menu item

   <source lang="java">
 

import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import javax.swing.ButtonGroup; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class SingleChoiceMenu extends JFrame {

 public static final String FontName[] = { "Serif", "SansSerif", "Courier" };
 private Font[] fonts;
 protected JMenuItem[] fontMenus;
 public SingleChoiceMenu() {
   super("BasicTextEditor with JColorChooser");
   setSize(450, 350);
   fonts = new Font[FontName.length];
   for (int k = 0; k < FontName.length; k++)
     fonts[k] = new Font(FontName[k], Font.PLAIN, 12);
   JMenuBar menuBar = createMenuBar();
   setJMenuBar(menuBar);
   WindowListener wndCloser = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(wndCloser);
   setVisible(true);
 }
 protected JMenuBar createMenuBar() {
   final JMenuBar menuBar = new JMenuBar();
   JMenu mFont = new JMenu("Font");
   mFont.setMnemonic("o");
   ButtonGroup group = new ButtonGroup();
   fontMenus = new JMenuItem[FontName.length];
   for (int k = 0; k < FontName.length; k++) {
     int m = k + 1;
     fontMenus[k] = new JRadioButtonMenuItem(m + " " + FontName[k]);
     boolean selected = (k == 0);
     fontMenus[k].setSelected(selected);
     fontMenus[k].setMnemonic("1" + k);
     fontMenus[k].setFont(fonts[k]);
     fontMenus[k].addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent arg0) {
         System.out.println(((JComponent) arg0.getSource())
             .getFont());
       }
     });
     group.add(fontMenus[k]);
     mFont.add(fontMenus[k]);
   }
   menuBar.add(mFont);
   return menuBar;
 }
 public static void main(String argv[]) {
   new SingleChoiceMenu();
 }

}



 </source>
   
  
 
  



React to menu action and checkbox menu

   <source lang="java">
 

import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.File; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JRadioButtonMenuItem; public class MenuDemo extends JFrame {

 public static final String FontNames[] = { "Serif", "SansSerif", "Courier" };
 protected Font fontArray[];
 protected JMenuItem[] menus;
 protected JCheckBoxMenuItem boldMenuItem;
 protected JCheckBoxMenuItem italicMenuItem;
 protected JFileChooser fileChooser;
 public MenuDemo() {
   super("Basic text editor");
   setSize(450, 350);
   fontArray = new Font[FontNames.length];
   for (int i = 0; i < FontNames.length; i++)
     fontArray[i] = new Font(FontNames[i], Font.PLAIN, 12);
   JMenuBar menuBar = createMenuBar();
   setJMenuBar(menuBar);
   fileChooser = new JFileChooser();
   fileChooser.setCurrentDirectory(new File("."));
   WindowListener exitEvent = new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   };
   addWindowListener(exitEvent);
   updateMonitor();
   setVisible(true);
 }
 protected JMenuBar createMenuBar() {
   final JMenuBar menuBar = new JMenuBar();
   JMenu menuFile = new JMenu("File");
   menuFile.setMnemonic("f");
   JMenuItem menuItem = new JMenuItem("New");
   menuItem.setIcon(new ImageIcon("file_new.gif"));
   menuItem.setMnemonic("n");
   ActionListener lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.out.println("New");
     }
   };
   menuItem.addActionListener(lst);
   menuFile.add(menuItem);
   menuItem = new JMenuItem("Open...");
   menuItem.setIcon(new ImageIcon("file_open.gif"));
   menuItem.setMnemonic("o");
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       MenuDemo.this.repaint();
       if (fileChooser.showOpenDialog(MenuDemo.this) != JFileChooser.APPROVE_OPTION)
         return;
       System.out.println(fileChooser.getSelectedFile());
     }
   };
   menuItem.addActionListener(lst);
   menuFile.add(menuItem);
   menuItem = new JMenuItem("Save...");
   menuItem.setIcon(new ImageIcon("file_save.gif"));
   menuItem.setMnemonic("s");
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.out.println("Save...");
     }
   };
   menuItem.addActionListener(lst);
   menuFile.add(menuItem);
   menuFile.addSeparator();
   menuItem = new JMenuItem("Exit");
   menuItem.setMnemonic("x");
   lst = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.exit(0);
     }
   };
   menuItem.addActionListener(lst);
   menuFile.add(menuItem);
   menuBar.add(menuFile);
   ActionListener fontListener = new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       updateMonitor();
     }
   };
   JMenu mFont = new JMenu("Font");
   mFont.setMnemonic("o");
   ButtonGroup group = new ButtonGroup();
   menus = new JMenuItem[FontNames.length];
   for (int i = 0; i < FontNames.length; i++) {
     int m = i + 1;
     menus[i] = new JRadioButtonMenuItem(m + " " + FontNames[i]);
     boolean selected = (i == 0);
     menus[i].setSelected(selected);
     menus[i].setMnemonic("1" + i);
     menus[i].setFont(fontArray[i]);
     menus[i].addActionListener(fontListener);
     group.add(menus[i]);
     mFont.add(menus[i]);
   }
   mFont.addSeparator();
   boldMenuItem = new JCheckBoxMenuItem("Bold");
   boldMenuItem.setMnemonic("b");
   Font fn = fontArray[1].deriveFont(Font.BOLD);
   boldMenuItem.setFont(fn);
   boldMenuItem.setSelected(false);
   boldMenuItem.addActionListener(fontListener);
   mFont.add(boldMenuItem);
   italicMenuItem = new JCheckBoxMenuItem("Italic");
   italicMenuItem.setMnemonic("i");
   fn = fontArray[1].deriveFont(Font.ITALIC);
   italicMenuItem.setFont(fn);
   italicMenuItem.setSelected(false);
   italicMenuItem.addActionListener(fontListener);
   mFont.add(italicMenuItem);
   menuBar.add(mFont);
   return menuBar;
 }
 protected void updateMonitor() {
   int index = -1;
   for (int k = 0; k < menus.length; k++) {
     if (menus[k].isSelected()) {
       index = k;
       break;
     }
   }
   if (index == -1)
     return;
   if (index == 2) // Courier
   {
     boldMenuItem.setSelected(false);
     boldMenuItem.setEnabled(false);
     italicMenuItem.setSelected(false);
     italicMenuItem.setEnabled(false);
   } else {
     boldMenuItem.setEnabled(true);
     italicMenuItem.setEnabled(true);
   }
   int style = Font.PLAIN;
   if (boldMenuItem.isSelected())
     style |= Font.BOLD;
   if (italicMenuItem.isSelected())
     style |= Font.ITALIC;
 }
 public static void main(String argv[]) {
   new MenuDemo();
 }

}


 </source>
   
  
 
  



Separating Menu Items in a Menu

   <source lang="java">
 

import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JSeparator; public class Main {

 public static void main(String[] argv) throws Exception {
   JMenu menu = new JMenu("Menu Label");
   JMenuItem item1 = new JMenuItem("Item Label");
   menu.add(item1);
   // Add separator
   menu.add(new JSeparator());
   // Add another menu item
   JMenuItem item2 = new JMenuItem("Item Label");
   menu.add(item2);
 }

}


 </source>
   
  
 
  



Simple Menu and Window interface - not Internationalized

   <source lang="java">
 

/*

* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
* 
* Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
* pioneering role in inventing and promulgating (and standardizing) the Java 
* language and environment is gratefully acknowledged.
* 
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/

/// import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; /**

* Simple Menu and Window interface - not Internationalized.
* 
* @author Ian Darwin
*/

public class JiltBefore extends JFrame implements ActionListener {

 JMenuBar mb;
 /** File, Options, Help */
 JMenu fm, om, hm;
 /** Options Sub-Menu */
 JMenu opSubm;
 /** The JMenuItem for exiting. */
 JMenuItem exitItem;
 // Constructor
 JiltBefore(String s) {
   super("JiltBefore: " + s);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   mb = new JMenuBar();
   setJMenuBar(mb);
   JMenuItem mi;
   // The File Menu...
   fm = new JMenu("File");
   fm.add(mi = new JMenuItem("Open"));
   mi.addActionListener(this);
   fm.add(mi = new JMenuItem("Close"));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new JMenuItem("Print"));
   mi.addActionListener(this);
   fm.addSeparator();
   fm.add(mi = new JMenuItem("Exit"));
   exitItem = mi; // save for action handler
   mi.addActionListener(this);
   mb.add(fm);
   // The Options Menu...
   om = new JMenu("Options");
   fm.add(mi = new JMenuItem("Enable"));
   opSubm = new JMenu("SubOptions");
   opSubm.add(new JMenuItem("Alpha"));
   opSubm.add(new JMenuItem("Gamma"));
   opSubm.add(new JMenuItem("Delta"));
   om.add(opSubm);
   mb.add(om);
   // The Help Menu...
   hm = new JMenu("Help");
   hm.add(mi = new JMenuItem("About"));
   mi.addActionListener(this);
   hm.add(mi = new JMenuItem("Topics"));
   mi.addActionListener(this);
   mb.add(hm);
   // mb.setHelpMenu(hm); // needed for portability (Motif, etc.).
   // the main window
   cp.add(new JLabel("Menu Demo Window"));
   // pack();
   setSize(250, 200);
 }
 /** Handle action events. */
 public void actionPerformed(ActionEvent evt) {
   // System.out.println("Event " + evt);
   String cmd;
   if ((cmd = evt.getActionCommand()) == null)
     System.out.println("You chose a menu shortcut");
   else
     System.out.println("You chose " + cmd);
   Object cmp = evt.getSource();
   // System.out.println("Source " + cmp);
   if (cmp == exitItem)
     System.exit(0);
 }
 public static void main(String[] arg) {
   new JiltBefore("Testing 1 2 3...").setVisible(true);
 }

}


 </source>
   
  
 
  



Simple Menus

   <source lang="java">
 

// : c14:SimpleMenus.java // <applet code=SimpleMenus width=200 height=75></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JTextField; public class SimpleMenus extends JApplet {

 private JTextField t = new JTextField(15);
 private ActionListener al = new ActionListener() {
   public void actionPerformed(ActionEvent e) {
     t.setText(((JMenuItem) e.getSource()).getText());
   }
 };
 private JMenu[] menus = { new JMenu("Winken"), new JMenu("Blinken"),
     new JMenu("Nod") };
 private JMenuItem[] items = { new JMenuItem("Fee"), new JMenuItem("Fi"),
     new JMenuItem("Fo"), new JMenuItem("Zip"), new JMenuItem("Zap"),
     new JMenuItem("Zot"), new JMenuItem("Olly"), new JMenuItem("Oxen"),
     new JMenuItem("Free") };
 public void init() {
   for (int i = 0; i < items.length; i++) {
     items[i].addActionListener(al);
     menus[i % 3].add(items[i]);
   }
   JMenuBar mb = new JMenuBar();
   for (int i = 0; i < menus.length; i++)
     mb.add(menus[i]);
   setJMenuBar(mb);
   Container cp = getContentPane();
   cp.setLayout(new FlowLayout());
   cp.add(t);
 }
 public static void main(String[] args) {
   run(new SimpleMenus(), 200, 75);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~



 </source>
   
  
 
  



Submenus, checkbox menu items, swapping menus,mnemonics (shortcuts) and action commands

   <source lang="java">
 

// : c14:SwingMenus.java // Submenus, checkbox menu items, swapping menus, // mnemonics (shortcuts) and action commands. // <applet code=SwingMenus width=300 height=100></applet> // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.BorderLayout; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyEvent; import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JCheckBoxMenuItem; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JTextField; public class SwingMenus extends JApplet {

 private String[] flavors = { "Chocolate", "Strawberry",
     "Vanilla Fudge Swirl", "Mint Chip", "Mocha Almond Fudge",
     "Rum Raisin", "Praline Cream", "Mud Pie" };
 private JTextField t = new JTextField("No flavor", 30);
 private JMenuBar mb1 = new JMenuBar();
 private JMenu f = new JMenu("File"), m = new JMenu("Flavors"),
     s = new JMenu("Safety");
 // Alternative approach:
 private JCheckBoxMenuItem[] safety = { new JCheckBoxMenuItem("Guard"),
     new JCheckBoxMenuItem("Hide") };
 private JMenuItem[] file = { new JMenuItem("Open") };
 // A second menu bar to swap to:
 private JMenuBar mb2 = new JMenuBar();
 private JMenu fooBar = new JMenu("fooBar");
 private JMenuItem[] other = {
 // Adding a menu shortcut (mnemonic) is very
     // simple, but only JMenuItems can have them
     // in their constructors:
     new JMenuItem("Foo", KeyEvent.VK_F),
     new JMenuItem("Bar", KeyEvent.VK_A),
     // No shortcut:
     new JMenuItem("Baz"), };
 private JButton b = new JButton("Swap Menus");
 class BL implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JMenuBar m = getJMenuBar();
     setJMenuBar(m == mb1 ? mb2 : mb1);
     validate(); // Refresh the frame
   }
 }
 class ML implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JMenuItem target = (JMenuItem) e.getSource();
     String actionCommand = target.getActionCommand();
     if (actionCommand.equals("Open")) {
       String s = t.getText();
       boolean chosen = false;
       for (int i = 0; i < flavors.length; i++)
         if (s.equals(flavors[i]))
           chosen = true;
       if (!chosen)
         t.setText("Choose a flavor first!");
       else
         t.setText("Opening " + s + ". Mmm, mm!");
     }
   }
 }
 class FL implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     JMenuItem target = (JMenuItem) e.getSource();
     t.setText(target.getText());
   }
 }
 // Alternatively, you can create a different
 // class for each different MenuItem. Then you
 // Don"t have to figure out which one it is:
 class FooL implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     t.setText("Foo selected");
   }
 }
 class BarL implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     t.setText("Bar selected");
   }
 }
 class BazL implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     t.setText("Baz selected");
   }
 }
 class CMIL implements ItemListener {
   public void itemStateChanged(ItemEvent e) {
     JCheckBoxMenuItem target = (JCheckBoxMenuItem) e.getSource();
     String actionCommand = target.getActionCommand();
     if (actionCommand.equals("Guard"))
       t.setText("Guard the Ice Cream! " + "Guarding is "
           + target.getState());
     else if (actionCommand.equals("Hide"))
       t.setText("Hide the Ice Cream! " + "Is it hidden? "
           + target.getState());
   }
 }
 public void init() {
   ML ml = new ML();
   CMIL cmil = new CMIL();
   safety[0].setActionCommand("Guard");
   safety[0].setMnemonic(KeyEvent.VK_G);
   safety[0].addItemListener(cmil);
   safety[1].setActionCommand("Hide");
   safety[1].setMnemonic(KeyEvent.VK_H);
   safety[1].addItemListener(cmil);
   other[0].addActionListener(new FooL());
   other[1].addActionListener(new BarL());
   other[2].addActionListener(new BazL());
   FL fl = new FL();
   for (int i = 0; i < flavors.length; i++) {
     JMenuItem mi = new JMenuItem(flavors[i]);
     mi.addActionListener(fl);
     m.add(mi);
     // Add separators at intervals:
     if ((i + 1) % 3 == 0)
       m.addSeparator();
   }
   for (int i = 0; i < safety.length; i++)
     s.add(safety[i]);
   s.setMnemonic(KeyEvent.VK_A);
   f.add(s);
   f.setMnemonic(KeyEvent.VK_F);
   for (int i = 0; i < file.length; i++) {
     file[i].addActionListener(fl);
     f.add(file[i]);
   }
   mb1.add(f);
   mb1.add(m);
   setJMenuBar(mb1);
   t.setEditable(false);
   Container cp = getContentPane();
   cp.add(t, BorderLayout.CENTER);
   // Set up the system for swapping menus:
   b.addActionListener(new BL());
   b.setMnemonic(KeyEvent.VK_S);
   cp.add(b, BorderLayout.NORTH);
   for (int i = 0; i < other.length; i++)
     fooBar.add(other[i]);
   fooBar.setMnemonic(KeyEvent.VK_B);
   mb2.add(fooBar);
 }
 public static void main(String[] args) {
   run(new SwingMenus(), 300, 100);
 }
 public static void run(JApplet applet, int width, int height) {
   JFrame frame = new JFrame();
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.getContentPane().add(applet);
   frame.setSize(width, height);
   applet.init();
   applet.start();
   frame.setVisible(true);
 }

} ///:~


 </source>
   
  
 
  



This example create a menubar and toolbar both populated with Action

   <source lang="java">
 

/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly

  • /

// MenuActionExample.java //This example create a menubar and toolbar both populated with Action //objects. // import java.awt.BorderLayout; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JToolBar; import javax.swing.border.BevelBorder; import javax.swing.border.EtchedBorder; public class MenuActionExample extends JPanel {

 public JMenuBar menuBar;
 public JToolBar toolBar;
 public MenuActionExample() {
   super(true);
   // Create a menu bar and give it a bevel border.
   menuBar = new JMenuBar();
   menuBar.setBorder(new BevelBorder(BevelBorder.RAISED));
   // Create a menu and add it to the menu bar.
   JMenu menu = new JMenu("Menu");
   menuBar.add(menu);
   // Create a toolbar and give it an etched border.
   toolBar = new JToolBar();
   toolBar.setBorder(new EtchedBorder());
   // Instantiate a sample action with the NAME property of
   // "Download" and the appropriate SMALL_ICON property.
   SampleAction exampleAction = new SampleAction("Download",
       new ImageIcon("action.gif"));
   // Finally, add the sample action to the menu and the toolbar.
   // These methods are no longer preferred:
   // menu.add(exampleAction);
   // toolBar.add(exampleAction);
   // Instead, you should create actual menu items and buttons:
   JMenuItem exampleItem = new JMenuItem(exampleAction);
   JButton exampleButton = new JButton(exampleAction);
   menu.add(exampleItem);
   toolBar.add(exampleButton);
 }
 class SampleAction extends AbstractAction {
   // This is our sample action. It must have an actionPerformed() method,
   // which is called when the action should be invoked.
   public SampleAction(String text, Icon icon) {
     super(text, icon);
   }
   public void actionPerformed(ActionEvent e) {
     System.out.println("Action [" + e.getActionCommand()
         + "] performed!");
   }
 }
 public static void main(String s[]) {
   MenuActionExample example = new MenuActionExample();
   JFrame frame = new JFrame("Action Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.setJMenuBar(example.menuBar);
   frame.getContentPane().add(example.toolBar, BorderLayout.NORTH);
   frame.setSize(200, 200);
   frame.setVisible(true);
 }

}


 </source>
   
  
 
  



Toggle Menu Item

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.Color; import java.awt.ruponent; import java.awt.Event; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import javax.swing.Action; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.Icon; 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.JRadioButtonMenuItem; import javax.swing.JToggleButton; import javax.swing.KeyStroke; import javax.swing.MenuElement; import javax.swing.MenuSelectionManager; import javax.swing.event.MouseInputListener; public class ToggleSample {

 public static void main(String args[]) {
   JFrame frame = new JFrame("JToggleButtonMenuItem Example");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   JMenuBar bar = new JMenuBar();
   JMenu file = new JMenu("File");
   file.setMnemonic("f");
   JMenuItem newItem = new JMenuItem("New", "N");
   file.add(newItem);
   JMenuItem openItem = new JMenuItem("Open", "O");
   file.add(openItem);
   JMenuItem closeItem = new JMenuItem("Close", "C");
   file.add(closeItem);
   file.addSeparator();
   JMenuItem saveItem = new JMenuItem("Save", "S");
   file.add(saveItem);
   file.addSeparator();
   JMenuItem exitItem = new JMenuItem("Exit", "X");
   file.add(exitItem);
   bar.add(file);
   JMenu edit = new JMenu("Edit");
   JMenuItem cutItem = new JMenuItem("Cut", "T");
   cutItem.setAccelerator(KeyStroke.getKeyStroke("X", Event.CTRL_MASK));
   edit.add(cutItem);
   JMenuItem copyItem = new JMenuItem("Copy", "C");
   copyItem.setAccelerator(KeyStroke.getKeyStroke("C", Event.CTRL_MASK));
   edit.add(copyItem);
   JMenuItem pasteItem = new JMenuItem("Paste", "P");
   pasteItem.setAccelerator(KeyStroke.getKeyStroke("V", Event.CTRL_MASK));
   pasteItem.setEnabled(false);
   edit.add(pasteItem);
   edit.addSeparator();
   JMenuItem findItem = new JMenuItem("Find", "F");
   findItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0));
   edit.add(findItem);
   edit.setMnemonic("e");
   Icon atIcon = new ImageIcon("at.gif");
   JMenu findOptions = new JMenu("Options");
   findOptions.setIcon(atIcon);
   findOptions.setMnemonic("O");
   ButtonGroup directionGroup = new ButtonGroup();
   JRadioButtonMenuItem forward = new JRadioButtonMenuItem("Forward", true);
   findOptions.add(forward);
   directionGroup.add(forward);
   JRadioButtonMenuItem backward = new JRadioButtonMenuItem("Backward");
   findOptions.add(backward);
   directionGroup.add(backward);
   findOptions.addSeparator();
   JCheckBoxMenuItem caseItem = new JCheckBoxMenuItem("Case Insensitive");
   findOptions.add(caseItem);
   edit.add(findOptions);
   JToggleButtonMenuItem toggleItem = new JToggleButtonMenuItem(
       "Ballon Help");
   toggleItem.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {
       System.out.println("Selected");
     }
   });
   edit.add(toggleItem);
   bar.add(edit);
   frame.setJMenuBar(bar);
   frame.setSize(350, 250);
   frame.setVisible(true);
 }

} class JToggleButtonMenuItem extends JToggleButton implements MenuElement {

 Color savedForeground = null;
 private static MenuElement NO_SUB_ELEMENTS[] = new MenuElement[0];
 public JToggleButtonMenuItem() {
   init();
 }
 public JToggleButtonMenuItem(String label) {
   super(label);
   init();
 }
 public JToggleButtonMenuItem(String label, Icon icon) {
   super(label, icon);
   init();
 }
 public JToggleButtonMenuItem(Action action) {
   super(action);
   init();
 }
 private void init() {
   updateUI();
   setRequestFocusEnabled(false);
   // Borrows heavily from BasicMenuUI
   MouseInputListener mouseInputListener = new MouseInputListener() {
     // If mouse released over this menu item, activate it
     public void mouseReleased(MouseEvent mouseEvent) {
       MenuSelectionManager menuSelectionManager = MenuSelectionManager
           .defaultManager();
       Point point = mouseEvent.getPoint();
       if ((point.x >= 0) && (point.x < getWidth()) && (point.y >= 0)
           && (point.y < getHeight())) {
         menuSelectionManager.clearSelectedPath();
         // component automatically handles "selection" at this point
         // doClick(0); // not necessary
       } else {
         menuSelectionManager.processMouseEvent(mouseEvent);
       }
     }
     // If mouse moves over menu item, add to selection path, so it
     // becomes armed
     public void mouseEntered(MouseEvent mouseEvent) {
       MenuSelectionManager menuSelectionManager = MenuSelectionManager
           .defaultManager();
       menuSelectionManager.setSelectedPath(getPath());
     }
     // When mouse moves away from menu item, disaarm it and select
     // something else
     public void mouseExited(MouseEvent mouseEvent) {
       MenuSelectionManager menuSelectionManager = MenuSelectionManager
           .defaultManager();
       MenuElement path[] = menuSelectionManager.getSelectedPath();
       if (path.length > 1) {
         MenuElement newPath[] = new MenuElement[path.length - 1];
         for (int i = 0, c = path.length - 1; i < c; i++) {
           newPath[i] = path[i];
         }
         menuSelectionManager.setSelectedPath(newPath);
       }
     }
     // Pass along drag events
     public void mouseDragged(MouseEvent mouseEvent) {
       MenuSelectionManager.defaultManager().processMouseEvent(
           mouseEvent);
     }
     public void mouseClicked(MouseEvent mouseEvent) {
     }
     public void mousePressed(MouseEvent mouseEvent) {
     }
     public void mouseMoved(MouseEvent mouseEvent) {
     }
   };
   addMouseListener(mouseInputListener);
   addMouseMotionListener(mouseInputListener);
 }
 // MenuElement methods
 public Component getComponent() {
   return this;
 }
 public MenuElement[] getSubElements() {
   // no subelements
   return NO_SUB_ELEMENTS;
 }
 public void menuSelectionChanged(boolean isIncluded) {
   ButtonModel model = getModel();
   // only change armed state if different
   if (model.isArmed() != isIncluded) {
     model.setArmed(isIncluded);
   }
   if (isIncluded) {
     savedForeground = getForeground();
     if (!savedForeground.equals(Color.blue)) {
       setForeground(Color.blue);
     } else {
       // In case foreground blue, use something different
       setForeground(Color.red);
     }
   } else {
     setForeground(savedForeground);
     // if null, get foreground from installed look and feel
     if (savedForeground == null) {
       updateUI();
     }
   }
 }
 public void processKeyEvent(KeyEvent keyEvent, MenuElement path[],
     MenuSelectionManager manager) {
   // If user presses space while menu item armed, select it
   if (getModel().isArmed()) {
     int keyChar = keyEvent.getKeyChar();
     if (keyChar == KeyEvent.VK_SPACE) {
       manager.clearSelectedPath();
       doClick(0); // inherited from AbstractButton
     }
   }
 }
 public void processMouseEvent(MouseEvent mouseEvent, MenuElement path[],
     MenuSelectionManager manager) {
   // For when mouse dragged over menu and button released
   if (mouseEvent.getID() == MouseEvent.MOUSE_RELEASED) {
     manager.clearSelectedPath();
     doClick(0); // inherited from AbstractButton
   }
 }
 // Borrows heavily from BasicMenuItemUI.getPath()
 private MenuElement[] getPath() {
   MenuSelectionManager menuSelectionManager = MenuSelectionManager
       .defaultManager();
   MenuElement oldPath[] = menuSelectionManager.getSelectedPath();
   MenuElement newPath[];
   int oldPathLength = oldPath.length;
   if (oldPathLength == 0)
     return new MenuElement[0];
   Component parent = getParent();
   if (oldPath[oldPathLength - 1].getComponent() == parent) {
     // Going deeper under the parent menu
     newPath = new MenuElement[oldPathLength + 1];
     System.arraycopy(oldPath, 0, newPath, 0, oldPathLength);
     newPath[oldPathLength] = this;
   } else {
     // Sibling/child menu item currently selected
     int newPathPosition;
     for (newPathPosition = oldPath.length - 1; newPathPosition >= 0; newPathPosition--) {
       if (oldPath[newPathPosition].getComponent() == parent) {
         break;
       }
     }
     newPath = new MenuElement[newPathPosition + 2];
     System.arraycopy(oldPath, 0, newPath, 0, newPathPosition + 1);
     newPath[newPathPosition + 1] = this;
   }
   return newPath;
 }

}


 </source>
   
  
 
  



UseActions: Menu

   <source lang="java">
 

/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress

  • /

import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import javax.swing.text.DefaultEditorKit; public class UseActions {

 public static void main(String args[]) {
   JFrame frame = new JFrame("Use TextAction");
   Container contentPane = frame.getContentPane();
   Dimension empty = new Dimension(0, 0);
   final JTextArea leftArea = new JTextArea();
   JScrollPane leftScrollPane = new JScrollPane(leftArea);
   leftScrollPane.setPreferredSize(empty);
   final JTextArea rightArea = new JTextArea();
   JScrollPane rightScrollPane = new JScrollPane(rightArea);
   rightScrollPane.setPreferredSize(empty);
   JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
       leftScrollPane, rightScrollPane);
   JMenuBar menuBar = new JMenuBar();
   frame.setJMenuBar(menuBar);
   JMenu menu = new JMenu("Options");
   menuBar.add(menu);
   JMenuItem menuItem;
   Action readAction = leftArea.getActionMap().get(
       DefaultEditorKit.readOnlyAction);
   menuItem = menu.add(readAction);
   menuItem.setText("Make read-only");
   Action writeAction = leftArea.getActionMap().get(
       DefaultEditorKit.writableAction);
   menuItem = menu.add(writeAction);
   menuItem.setText("Make writable");
   menu.addSeparator();
   Action cutAction = leftArea.getActionMap().get(
       DefaultEditorKit.cutAction);
   menuItem = menu.add(cutAction);
   menuItem.setText("Cut");
   Action copyAction = leftArea.getActionMap().get(
       DefaultEditorKit.copyAction);
   menuItem = menu.add(copyAction);
   menuItem.setText("Copy");
   Action pasteAction = leftArea.getActionMap().get(
       DefaultEditorKit.pasteAction);
   menuItem = menu.add(pasteAction);
   menuItem.setText("Paste");
   contentPane.add(splitPane, BorderLayout.CENTER);
   frame.setSize(400, 250);
   frame.setVisible(true);
   splitPane.setDividerLocation(.5);
 }

}


 </source>