4. Swing Menus

The following applet shows many of the menu features you're likely to use.

Figure 10.18. Menu

Menu

4.1. Menu Components

  • JMenuBar

    Represents the platform-dependent notion of a group of menus attached to a window. JMenuBars cannot be bound to JPanels.

  • JPopupmenu

    Represents a popup menu.

  • JSeparator

    Implements a divider line to separate groups of menu itens.

  • JMenuItem

    Each item in a menu is represented by a JMenuItem object.

  • JMenu

    JMenu enables you to create submenus by adding one menu to another.

  • JCheckboxMenuItem

    Is a menu item that implements a check box.

  • JRadioButtonMenuItem

    Is a menu item that implements a radio button, in which only one item in a group can be selected.

Figure 10.19. Menu-related classes hierarchy

Menu-related classes hierarchy

4.2. MenuContainer Interface

To be able to contain a menu component, an object must adhere to the MenuContainer interface (JFrame, JMenu, and JMenuBar classes do)

4.3. Code Example

public class MenuWindow extends JFrame 
    implements ActionListener, ItemListener {
    . . .
    public MenuWindow() {
        
        // Build the menu bar.
        mb = new JMenuBar();
        setJMenuBar(mb);
 
        // Build first menu in the menu bar.
        m1 = new JMenu("Menu 1", true);
        mb.add(m1);

        mi1_1 = new JMenuItem("Menu Item 1_1");
        m1.add(mi1_1);
        . . .

        // Build help menu.
        m5 = new JMenu("Menu 5");
        mb.add(m5); //just setting the help menu doesn't work; must add it
        mb.setHelpMenu(m5);

        mi5_1 = new JMenuItem("Menu Item 5_1");
        mi5_1.setMnemonic(KeyEvent.VK_5);
        m5.add(mi5_1);
        . . .

        // Build second menu in the menu bar.
        m2 = new JMenu("Menu 2");
        mb.add(m2);

        mi2_1 = new JCheckboxMenuItem("Menu Item 2_1");
        m2.add(mi2_1);
 
        // Build third menu in the menu bar.
        . . .
        
        // Register as an ActionListener for all menu items.
        m1.addActionListener(this);
        m2.addActionListener(this);
        m3.addActionListener(this);
                . . .
        // Register as ItemListener on checkbox menu item.
        mi2_1.addItemListener(this);
    }
    . . .
    public void actionPerformed(ActionEvent e) {
        output.append("\"" + e.getActionCommand() +
                      "\" action detected in menu labeled \"" +
                      ((JMenuItem)(e.getSource())).getLabel() + "\".\n");
    }

    public void itemStateChanged(ItemEvent e) {
        output.append("Item state change detected on item \"" +
                      e.getItem() + "\" (state is " +
                      ((e.getStateChange() == ItemEvent.SELECTED)? 
                            "selected)." : "deselected).") + "\n");
    }
}