com.cleancode.swing
Class JMenuBarMgr

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by javax.swing.JComponent
              extended by javax.swing.JMenuBar
                  extended by com.cleancode.swing.JMenuBarMgr
All Implemented Interfaces:
ImageObserver, MenuContainer, Serializable, Accessible, MenuElement

public class JMenuBarMgr
extends JMenuBar

Manages a JMenuBar, providing convenient tools for building menus. This is a general-purpose menu manager which automatically handles radio button grouping and mnemonic assignments within each menu, and mnemonic assignments for the set of menus themselves. All menu items are assigned the same ActionListener.

The JMenuBarMgr class makes it straightforward to create an entire menu bar. Create a list of JMenuItemSpec objects for each menu, each of which can be quite short since there are default settings for several properties. Next create a list of JMenuSpec objects from the JMenuItemSpec objects, and pass that in to the createMenu method. Here's a sample fragment:


        final JMenuItemSpec[] fileItems = {
                new JMenuItemSpec(new JCheckBoxMenuItem("Work Offline"),
                CMD_OFFLINE, KeyEvent.VK_W),
                new JMenuItemSpec(), // separator
                new JMenuItemSpec(new JMenuItem("Save History"),CMD_SAVE_HISTORY),
                new JMenuItemSpec(), // separator
                new JMenuItemSpec(new JMenuItem("Exit"),
                KeyEvent.VK_X,CMD_EXIT, KeyEvent.VK_F4, ActionEvent.ALT_MASK)
        }
        . . .
        final JMenuSpec[] menuList = {
                new JMenuSpec("File", fileItems),
                . . .
        }
 
Note that the simplest item is an empty JMenuItemSpec, which is a separator. The next simplest contains just a JMenuItem and a command. Any such menu item will still have a mnemonic key assigned (though not an accelerator), so that could suffice for many tasks.

Since:
CleanCode 0.9
Version:
$Revision: 9 $
Author:
Michael Sorens
See Also:
JMenuSpec, JMenuItemSpec, Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class javax.swing.JMenuBar
JMenuBar.AccessibleJMenuBar
 
Nested classes/interfaces inherited from class javax.swing.JComponent
JComponent.AccessibleJComponent
 
Nested classes/interfaces inherited from class java.awt.Container
Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
Component.AccessibleAWTComponent, Component.BaselineResizeBehavior, Component.BltBufferStrategy, Component.FlipBufferStrategy
 
Field Summary
static String VERSION
          Current version of this class.
 
Fields inherited from class javax.swing.JComponent
accessibleContext, listenerList, TOOL_TIP_TEXT_KEY, ui, UNDEFINED_CONDITION, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT, WHEN_FOCUSED, WHEN_IN_FOCUSED_WINDOW
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
JMenuBarMgr(ActionListener listener)
          Creates a new JMenuBarMgr, a wrapper for a JMenuBar.
 
Method Summary
 JMenu buildMenu(JMenuSpec menuSpec)
          Builds a single menu.
 void createMenus(JMenuSpec[] menuList)
          Creates the menus for the JMenuBar, attaching them to the menu bar.
 JMenuItem getMenuItem(String cmd)
          Returns a JMenuItem within a menu on the JMenuBar.
 
Methods inherited from class javax.swing.JMenuBar
add, addNotify, getAccessibleContext, getComponent, getComponentAtIndex, getComponentIndex, getHelpMenu, getMargin, getMenu, getMenuCount, getSelectionModel, getSubElements, getUI, getUIClassID, isBorderPainted, isSelected, menuSelectionChanged, paintBorder, paramString, processKeyBinding, processKeyEvent, processMouseEvent, removeNotify, setBorderPainted, setHelpMenu, setMargin, setSelected, setSelectionModel, setUI, updateUI
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addVetoableChangeListener, computeVisibleRect, contains, createToolTip, disable, enable, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBaseline, getBaselineResizeBehavior, getBorder, getBounds, getClientProperty, getComponentGraphics, getComponentPopupMenu, getConditionForKeyStroke, getDebugGraphicsOptions, getDefaultLocale, getFontMetrics, getGraphics, getHeight, getInheritsPopupMenu, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getNextFocusableComponent, getPopupLocation, getPreferredSize, getRegisteredKeyStrokes, getRootPane, getSize, getToolTipLocation, getToolTipText, getToolTipText, getTopLevelAncestor, getTransferHandler, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, grabFocus, isDoubleBuffered, isLightweightComponent, isManagingFocus, isOpaque, isOptimizedDrawingEnabled, isPaintingForPrint, isPaintingTile, isRequestFocusEnabled, isValidateRoot, paint, paintChildren, paintComponent, paintImmediately, paintImmediately, print, printAll, printBorder, printChildren, printComponent, processComponentKeyEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removeVetoableChangeListener, repaint, repaint, requestDefaultFocus, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setComponentPopupMenu, setDebugGraphicsOptions, setDefaultLocale, setDoubleBuffered, setEnabled, setFocusTraversalKeys, setFont, setForeground, setInheritsPopupMenu, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setNextFocusableComponent, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setTransferHandler, setUI, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, getMousePosition, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paintComponents, preferredSize, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setComponentZOrder, setFocusCycleRoot, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getForeground, getGraphicsConfiguration, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getToolkit, getTreeLock, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, resize, resize, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

VERSION

public static final String VERSION
Current version of this class.

Constructor Detail

JMenuBarMgr

public JMenuBarMgr(ActionListener listener)
Creates a new JMenuBarMgr, a wrapper for a JMenuBar.

Parameters:
listener - an ActionListener which handles menu commands
Method Detail

createMenus

public void createMenus(JMenuSpec[] menuList)
Creates the menus for the JMenuBar, attaching them to the menu bar.

Each JMenuSpec specifies a list of menu items, an optional mnemonic, and an optional MenuListener. A JMenu is created for each by the buildMenu method (which automatically handles radio button grouping and mnemonic assignments at the item level), a mnemonic is assigned to the JMenu, and the optional MenuListener is attached, if provided.

Mnemonics are assigned automatically. Mnemonics are assigned at the menu level. Those that are provided in the JMenuSpec list are allocated first. The remaining menus are scanned assigning the first unique character available from each name. As an example, consider a set of menus named File, Edit, Tools, Run, and Results. One may invoke createMenus with none, some, or all, of them having explicit mnemonic assignments.

Parameters:
menuList - a list of menu specifications

buildMenu

public JMenu buildMenu(JMenuSpec menuSpec)
Builds a single menu. This routine is used internally by createMenus but is also public so that one may create a JMenu to be used as a sub-menu. Since JMenu is a subclass of JMenuItem, the resulting JMenu may be inserted into a JMenuItemSpec which is passed to createMenus.

For each menu item: Radio button are grouped automatically. As menu items are processed sequentially, adjacent radio buttons are grouped until either a separator or a non-radio button is encountered.

Mnemonics are assigned automatically. Mnemonics may or may not be provided in each JMenuItem. Those that are provided are allocated first. The remaining menu items are scanned assigning the first unique character available from each name.

Parameters:
menuSpec - a specification for a single menu
Returns:
a JMenu object containing the items in the menuSpec

getMenuItem

public JMenuItem getMenuItem(String cmd)
Returns a JMenuItem within a menu on the JMenuBar.

Parameters:
cmd - an actionCommand previously installed on a JMenuItem
Returns:
a JMenuItem corresponding to the actionCommand


CleanCode Java Libraries Copyright © 2001-2012 Michael Sorens - Revised 2012.12.10 Get CleanCode at SourceForge.net. Fast, secure and Free Open Source software downloads