Java Reference
In-Depth Information
// Borrows heavily from BasicMenuItemUI.getPath()
private MenuElement[] getPath() {
MenuSelectionManager menuSelectionManager =
MenuSelectionManager.defaultManager();
MenuElement oldPath[] = menuSelectionManager.getSelectedPath();
MenuElement newPath[];
int oldPathLength = oldPath.length;
if (oldPathLength == 0)
return new MenuElement[0];
Component parent = getParent();
if (oldPath[oldPathLength-1].getComponent() == parent) {
// Going deeper under the parent menu
newPath = new MenuElement[oldPathLength+1];
System.arraycopy(oldPath, 0, newPath, 0, oldPathLength);
newPath[oldPathLength] = this;
} else {
// Sibling/child menu item currently selected
int newPathPosition;
for (newPathPosition = oldPath.length-1; newPathPosition >= 0;
newPathPosition--) {
if (oldPath[newPathPosition].getComponent() == parent) {
break;
}
}
newPath = new MenuElement[newPathPosition+2];
System.arraycopy(oldPath, 0, newPath, 0, newPathPosition+1);
newPath[newPathPosition+1] = this;
}
return newPath;
}
}
■
Note
The
MouseInputListener
defined in the
init()
method and the
getPath()
method borrow
heavily from the system
BasicMenuUI
class. Normally, the user interface delegate deals with what happens
when the mouse moves over a menu component. Because the
JToggleButton
isn't a predefined menu
component, its UI class doesn't deal with it. For better modularity, these two methods should be moved into
an extended
ToggleButtonUI
.
Once you've created this
JToggleButtonMenuItem
class, you can use it like any other
menu item:
JToggleButtonMenuItem toggleItem = new JToggleButtonMenuItem("Balloon Help");
editMenu.add(toggleItem);