![]() |
The Java Developers Almanac 1.4 |
|
e813. Getting the Currently Selected Menu or Menu ItemThe currently selected menu or menu item in aJMenu or
JPopupMenu is tracked by MenuSelectionManager and can be
retrieved by calling MenuSelectionManager.getSelectedPath().
This method returns an array of MenuElement objects, representing
all the menu objects that are part of the selected menu or menu item.
For example, when a menu is opened in a menu bar, the sequence of
elements in the path is: JMenuBar, JMenu, and
JPopupMenu. If a menu item in the open menu is then selected,
there will be fourth element, a JMenuItem.
The menu path also includes nested menus. For example, if the
currently selected menu item is part of a nested menu in a menu bar,
the sequence of elements is: If a menu item in a popup menu is selected, the sequence of
menu objects is simply // Get the selected menu path
MenuElement[] path = MenuSelectionManager.defaultManager().getSelectedPath();
if (path.length == 0) {
// No menus are opened or menu items selected
}
// Retrieve the labels of all the menu elements in the path
for (int i=0; i<path.length; i++) {
Component c = path[i].getComponent();
if (c instanceof JMenuItem) {
JMenuItem mi = (JMenuItem)c;
String label = mi.getText();
// Note: JMenu is a subclass of JMenuItem; also JMenuBar does not have a label
}
}
e809. Separating Menu Items in a Menu e810. Creating a Popup Menu e811. Creating a Popup Menu with Nested Menus e812. Forcing a Popup Menu to Be a Heavyweight Component e814. Creating a Menu Item That Listens for Changes to Its Selection Status e815. Listening for Changes to the Currently Selected Menu or Menu Item © 2002 Addison-Wesley. |