Menu Demo : Menu « Swing JFC « Java






Menu Demo

Menu Demo
   

/*
 * 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.");
    }
  }
}


           
         
    
    
  








Related examples in the same category

1.Simple MenusSimple Menus
2.Creating popup menus with SwingCreating popup menus with Swing
3.Create a main menu.
4.Creating a menubar
5.Creating a JMenuBar, JMenu, and JMenuItem Component
6.Submenus, checkbox menu items, swapping menus,mnemonics (shortcuts) and action commandsSubmenus, checkbox menu items, swapping menus,mnemonics (shortcuts) and action commands
7.Separating Menu Items in a Menu
8.This example create a menubar and toolbar both populated with ActionThis example create a menubar and toolbar both populated with Action
9.A simple example of JPopupMenuA simple example of JPopupMenu
10.A quick demonstration of checkbox menu itemsA quick demonstration of checkbox menu items
11.Building menus and menu items: Accelerators and mnemonicsBuilding menus and menu items: Accelerators and mnemonics
12.An example of the JPopupMenu in actionAn example of the JPopupMenu in action
13.A simple example of constructing and using menus.A simple example of constructing and using menus.
14.PopupMenu and Mouse EventPopupMenu and Mouse Event
15.Menu YMenu Y
16.Menu XMenu X
17.Action MenuAction Menu
18.Menu Action Screen Dump DemoMenu Action Screen Dump Demo
19.Toggle Menu ItemToggle Menu Item
20.CheckBox Menu SampleCheckBox Menu Sample
21.Menu Demo 4Menu Demo 4
22.Comprehensive Menu DemoComprehensive Menu Demo
23.Menu Sample 3Menu Sample 3
24.How to create customized menuHow to create customized menu
25.Radio menu itemRadio menu item
26.React to menu action and checkbox menuReact to menu action and checkbox menu
27.Menu created from property file
28.Simple Menu and Window interface - not InternationalizedSimple Menu and Window interface - not Internationalized
29.Provide a pop-up menu using a FrameProvide a pop-up menu using a Frame
30.Demonstrate Menus and the MenuBar classDemonstrate Menus and the MenuBar class
31.Demonstrate JMenu shortcuts and accelerators
32.Demonstrate Cascading MenusDemonstrate Cascading Menus
33.Popup Menu DemoPopup Menu Demo
34.Menu Layout DemoMenu Layout Demo
35.Actions MenuBarActions MenuBar
36.UseActions: MenuUseActions: Menu
37.PopupMenu SamplePopupMenu Sample
38.RadioButton Menu SampleRadioButton Menu Sample
39.Menu Look Demo, except the menu items actually doMenu Look Demo, except the menu items actually do
40.Menu Glue DemoMenu Glue Demo
41.Add PopupMenuAdd PopupMenu
42.Listening for Changes to the Currently Selected Menu or Menu Item
43.Menu item that can be selected or deselected
44.Place commands that hide/show various toolbars
45.Getting the Currently Selected Menu or Menu Item
46.Creating a Menu Item That Listens for Changes to Its Selection Status
47.Create a change listener and register with the menu selection manager
48.Menu Selection Manager DemoMenu Selection Manager Demo
49.Color Menu
50.MenuBar, menu item, action, icon acceleratorMenuBar, menu item, action, icon accelerator