JavaSwingComponentsMenus: Basics


Basics

MenuElement

MenuElements can take part in menu selection and have special event dispatching.

Each MenuElement has an associated component (in the default implementations, this is the menu element itself). (Any component can be used, but it must have special event handling, see below). There is no way to get the MenuElement back from the component.

MenuElements form a tree (or possibly more general graph) structure (without parent references): each MenuElement has references to its sub elements (can the name be misunderstood to mean all descendants?). The tree need not coincide with the Container hierarchy (but typically is related).

Menu selection (MenuSelectionManager)

The global MenuSelectionManager instance (not exchangable) maintains a selected path of MenuElements (which may be empty). (Actually one may use custom subclasses, but the global instance is accessed all around and not passed around everywhere explicitly).

The selected path is set from the specific menu code (not from the MenuSelectionManager itself). It probably shouldn't be done by general code (instead use the features of the specific menu component at hand). It may have a hierarchy problem (is setting the selected path the reason for updating or vice-versa).

The selected path's changes are observable (only ChangeListener, thus the old selected path must be cached), and also the MenuElements are notified (menuSelectionChanged) that they are/are no more part of the selected path.

Menu mouse/key event dispatching

MenuElement components must dispatch the mouse and key events they receive to the MenuSelectionManager (this is unrelated to maintaining the selected path) which hands them around to members of the selected path and their sub elements. (This may include the component itself if it was part of the selected path or one its sub-elements' component).

For mouse events, this makes it possible to handle menus while the mouse is pressed (normally only the component the mouse originally was pressed on gets the mouse events).

It seems to imply that menu element components should only be visible (or focused) when at least their "parent" element is part of the selected path, otherwise it may not get the event back (? JMenus are visible all of the time when they are in JMenuBar).

Actually, the default implementations of MenuElement (and its surrounding classes) do not send all events.

Menu events (not directly related)

MenuEvent seems to be unrelated and (in the current implementation) specific to JMenu

MenuDragMouse- and MenuKeyEvent are used by JMenuItem (and then JMenu) to fire events for the MenuElement-dispatched events (so that the Menu(Item)UI classes can react to them in a listener-style way). Probably custom listeners do not make much sense.

PopupMenuEvent is specific for JPopupMenu (but also used by JComboBox)


(C) 2001-2009 Christian Kaufhold (swing@chka.de)