Keeping Menus Open
Posted by Darryl Burke on September 12, 2010
The default behavior of menus on all platforms, not just in Java, is for the menu to disappear when any item is selected. But once in a way, one comes across a situation where keeping the menu open could improve the user experience. For example, in the “Quick Preferences” submenu in Opera browser, a user who wants to set more than one option is forced to navigate the menu repeatedly.
Fortunately, the flexibility afforded in terms of extending the JDK classes makes this possible in Java.
While it is more trouble that it is worth to actually prevent a menu from closing when an item is clicked, instantly reopening the menu to the same selection has much the same effect. To do this requires the use of a less known Swing class, MenuSelectionManager. This is the class responsible for setting and clearing menu selections. It can also furnish details of the currently selected menu path.
So, keeping a menu open is a two stage process:
- Saving the menu path before the item is clicked.
- Restoring the saved path immediately after the click.
There are many ways in which the first stage might be approached. In these implementations, a ChangeListener added to the menu item’s ButtonModel is used to conditionally save the menu selection path in its stateChanged method when the model is armed and the menu item is showing. Since there can only ever be one menu item with an armed model, some economy is achieved by saving the path to a static field. The saved path is then restored in a minimal override to the doClick method.
Each of the classes provided is furnished with a full set of constructors that call into the constructors of the JDK classes they extend. Any of them can be used as a drop-in replacement in existing code without other modification.