The JMenuItem Class

Before discussing menus, we should introduce the JMenuItem class first. Figure 14-6 shows the class diagram for the JMenuItem component.

JMenuItem class diagram

Figure 14-6. JMenuItem class diagram

A JMenuItem serves as a wrapper for strings and images to be used as elements in a menu. We mentioned earlier that the JMenuItem class is essentially just a specialized button. In fact, the JMenuItem class extends the AbstractButton class. Its logic, however, is somewhat different from the standard button. When the mouse passes over a menu item, Swing considers the menu item to be selected. If the user releases the mouse over the menu item, it is considered chosen and should perform its action.

There is an unfortunate conflict in terminology here. Swing considers a menu item “selected” when the mouse moves over it, as updated by the MenuSelectionManager and classes that implement the MenuElement interface. On the other hand, Swing considers a button “selected” when it remains in one of two persistent states, such as a checkbox button remaining in the checked state until clicked again. So when a menu item is selected, its button model is really armed. Conversely, when a menu item is deselected, its button model is disarmed. Finally, when the user releases the mouse button over the menu item, the button is considered clicked and the AbstractButton’s doClick() method is invoked.

Menu Item Shortcuts ...

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.