O'Reilly logo

Java Swing by Dave Wood, Marc Loy, Robert Eckstein

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required