The JMenu Class

The JMenu class represents the anchored menus that are attached to a JMenuBar or another JMenu. Menus that are directly attached to a menubar are called top-level menus. Submenus, on the other hand, are not attached to a menubar but instead to an already existing menu item that serves as its title. This menu item title is typically marked by a right arrow, indicating that its menu will appear alongside the menu item if the user selects it. See Figure 14.11.

Top-level menus and submenus

Figure 14-11. Top-level menus and submenus

JMenu is a curious class. It contains a MenuUI delegate, but it uses a ButtonModel for its data model. To see why this is the case, it helps to visualize a menu as two components: a menu item and a popup menu. The menu item serves as the title. When it is pressed, it signals the popup menu to show itself either below or directly to the right of the menu item. JMenu actually extends the JMenuItem class, which makes it possible to implement the title portion of the menu. This, in effect, makes it a specialized button. Remember that you can use the mnemonic property of the JMenuItem superclass to define the shortcut for the menu’s title, and consequently the menu. In addition, you can use the enabled property of JMenuItem to disable the menu if desired.

As with popup menus, you can add or insert JMenuItem, Component, or Action objects to the popup portion of the menu by ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.