Java Reference
In-Depth Information
Creating Custom MenuElement Components:
The MenuElement Interface
One thing all the selectable menu components have in common is that they implement the
MenuElement
interface. The
JSeparator
doesn't implement the interface, but that's okay because
it isn't selectable. The purpose of the
MenuElement
interface is to allow the
MenuSelectionManager
to notify the different menu elements as a user moves around a program's menu structure.
As the following interface definition shows, the
MenuElement
interface is made up of
five methods:
public interface MenuElement {
public Component getComponent();
public MenuElement[] getSubElements();
public void menuSelectionChanged(boolean isInclude);
public void processKeyEvent(KeyEvent event, MenuElement path[],
MenuSelectionManager mgr);
public void processMouseEvent(MouseEvent event, MenuElement path[],
MenuSelectionManager mgr);
}
The
getComponent()
method returns the menu's rendering component. This is usually the
menu component itself, although that isn't a requirement. The
getSubElements()
method
returns an array of any menu elements contained within this element. If this menu element
isn't the top of a submenu, the method should return a zero-length array of
MenuElement
objects, not
null
.
The
menuSelectionChanged()
method is called whenever the menu item is placed in or
taken out of the selection path for the menu selection manager.
The two
processKeyEvent()
and
processMouseEvent()
methods are for processing a key
event or mouse event that's generated over a menu. How your menu item processes events
depends on what the component supports. For instance, unless you support accelerators, you
probably want to respond to key events only when your menu item is in the current selection
path.
■
Note
If, for example, your new menu element was something like a
JComboBoxMenuItem
, where the
MenuElement
acted like a
JComboBox
, the
processKeyEvent()
might pass along the key character to
the
KeySelectionManager
. See Chapter 13 for more on the
KeySelectionManager
.
To demonstrate the
MenuElement
interface, Listing 6-6 creates a new menu component
called a
JToggleButtonMenuItem
. This component will look and act like a
JToggleButton
, although
it can be on a menu. It's important to ensure that the menu goes away once the item is selected
and that the component is displayed differently when in the current selection path.