JSR-209 (Final Release)

javax.swing
Class JMenuBar

java.lang.Object
  extended byjava.awt.Component
      extended byjava.awt.Container
          extended byjavax.swing.JComponent
              extended byjavax.swing.JMenuBar
All Implemented Interfaces:
java.awt.image.ImageObserver, MenuElement, java.io.Serializable

public class JMenuBar
extends JComponent
implements MenuElement

An implementation of a menu bar. You add JMenu objects to the menu bar to construct a menu. When the user selects a JMenu object, its associated JPopupMenu is displayed, allowing the user to select one of the JMenuItems on it.

For information and examples of using menu bars see How to Use Menus, a section in The Java Tutorial.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeansTM has been added to the java.beans package. Please see java.beans.XMLEncoder.

Client properties for consumer devices (not included in J2SE 1.4.2)

A menubar is not a natural part of the use interface in many consumer devices, instead soft keys are often used in these devices. Like MenuItem, the soft keys are used to execute application specific actions. The number of soft keys is limited, which means that the implementation may need to change the menu hierarchy. For example, if the JMenuBar has three top-level JMenus but the device has two soft keys, the implementation need to cascade two menus onto one soft key.

The native UI style typically has a standard mapping of certain operations to specific soft keys. For example, an action to get back in the interaction is consistently assigned to the same soft key. To allow implementation to provide similar adaptation to native look and feel practices the application should provide semantic hints as client properties for JMenu and JMenuItem. An application can define hints by calling JComponent.putClientProperty() on the top-level JMenus in the JMenubar. Note that in AGUI an empty JMenu can act like a JMenuItem. (the reader may note similarities between the following sections and the MIDP 2.0 specification, these simalarities are intended) The following client properties can be set:

MENU_TYPE

The application uses this property to specify the intent of this action. For example, if the application specifies that the JMenuItem is of type "BACK", and if the device has a standard of placing the "back" operation on a certain soft-button, the implementation can follow the style of the device by using the semantic information as a guide. The type of the value of this property is String and the defined values for the property MENU_TYPE are:

Property Value
Description
BACK
A navigation command that returns the user to the logically previous screen.
CANCEL
A command that is a standard negative answer to a dialog implemented by current screen.
EXIT
A command used for exiting from the application.
HELP
This command specifies a request for on-line help.
ITEM
With this command type the application can hint to the implementation that the command is specific to the some selected item.
OK
A command that is a standard positive answer to a dialog implemented by current screen
SCREEN
Specifies an application-defined command that pertains to the current screen.
STOP
A command that will stop some currently running process, operation, etc

MENU_PRIORITY

The application uses the priority value to describe the importance of this command relative to other commands on the same screen. Priority values are integers, where a lower number indicates greater importance. The actual values are chosen by the application. A priority value of one might indicate the most important command, priority values of two, three, four, and so on indicate commands of lesser importance.

Typically, the implementation first chooses the placement of a command based on the type of command and then places similar commands based on a priority order. This could mean that the command with the highest priority is placed so that user can trigger it directly and that commands with lower priority are placed on a menu. It is not an error for there to be commands on the same screen with the same priorities and types. If this occurs, the implementation will choose the order in which they are displayed.

In a case where the device supports both menu bar and soft keys, the implementation MAY choose to map the JMenuItems marked with the above properties to soft keys while remaining menu hierarchy is put to the menu bar.

The algorithm in could be the following:

Examples

The following text is provided as an example only. Implementations are not required to follow this behavior.

The application wishes to use three actions mapped to soft keys:

 JMenuBar commands = new JMenuBar();
 JMenuItem buy = new JMenu("Buy");
 buy.putClientProperty("MENU_TYPE", "ITEM");
 buy.putClientProperty("MENU_PRIORITY", new Integer(1));
 commands.add(buy);

 JMenuItem info = new JMenu("Info");
 info.putClientProperty("MENU_TYPE", "ITEM");
 info.putClientProperty("MENU_PRIORITY", new Integer(1));
 commands.add(info);
 
 JMenuItem back = new JMenu("Back");
 back.putClientProperty("MENU_TYPE", "BACK");
 back.putClientProperty("MENU_PRIORITY", new Integer(1));
 commands.add(back);
 
 myFrame.setJMenuBar(commands);
 

In a device with three soft keys the result could be equal to the example shown in MIDP specs:

Soft Key Display 1

If the device has only two soft buttons, the implementation has to build a menu hierarchy:

Soft Key Display 2

When user presses the left soft button, a menu with the two remaining Commands appears:

Soft Key Display 3

Note that the application did not deliver any hierarchy in the above example. It is possible to deliver such hierarchy as follows:

 JMenuBar commands = new JMenuBar();
 JMenu jm = new JMenu("Options");
 jm.putClientProperty("MENU_TYPE", "ITEM");
 jm.putClientProperty("MENU_PRIORITY", new Integer(1));

  JMenuItem buy = new JMenuItem("Buy");
  jm.add(buy);
  JMenuItem info = new JMenuItem("Info");
  jm.add(info);

 jm.putClientProperty("MENU_PRIORITY", new Integer(1)); 
 commands.add(jm);
 
 JMenuItem back = new JMenu("Back");
 back.putClientProperty("MENU_TYPE", "BACK");
 back.putClientProperty("MENU_PRIORITY", new Integer(1));
 commands.add(back);
 

See Also:
JMenu, JPopupMenu, JMenuItem

Field Summary
 
Fields inherited from class javax.swing.JComponent
listenerList, TOOL_TIP_TEXT_KEY, 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
JMenuBar()
          Creates a new menu bar.
 
Method Summary
 JMenu add(JMenu c)
          Appends the specified menu to the end of the menu bar.
 void addNotify()
          Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.
 java.awt.Component getComponent()
          Implemented to be a MenuElement.
 int getComponentIndex(java.awt.Component c)
          Returns the index of the specified component.
 JMenu getHelpMenu()
          Gets the help menu for the menu bar.
 java.awt.Insets getMargin()
          Returns the margin between the menubar's border and its menus.
 JMenu getMenu(int index)
          Returns the menu at the specified position in the menu bar.
 int getMenuCount()
          Returns the number of items in the menu bar.
 SingleSelectionModel getSelectionModel()
          Returns the model object that handles single selections.
 MenuElement[] getSubElements()
          Implemented to be a MenuElement -- returns the menus in this menu bar.
 boolean isBorderPainted()
          Returns true if the menu bars border should be painted.
 boolean isSelected()
          Returns true if the menu bar currently has a component selected.
 void menuSelectionChanged(boolean isIncluded)
          Implemented to be a MenuElement -- does nothing.
 void paint(java.awt.Graphics g)
          Invoked by Swing to draw components.
protected  void paintBorder(java.awt.Graphics g)
          Paints the menubar's border if BorderPainted property is true.
protected  void paintComponent(java.awt.Graphics g)
          Calls the UI delegate's paint method, if the UI delegate is non-null.
 void paintComponents(java.awt.Graphics g)
           
protected  java.lang.String paramString()
          Returns a string representation of this JMenuBar.
protected  void printBorder(java.awt.Graphics g)
          Prints the component's border.
protected  void printComponent(java.awt.Graphics g)
          This is invoked during a printing operation.
 void printComponents(java.awt.Graphics g)
           
protected  boolean processKeyBinding(KeyStroke ks, java.awt.event.KeyEvent e, int condition, boolean pressed)
          Subclassed to check all the child menus.
 void processKeyEvent(java.awt.event.KeyEvent e, MenuElement[] path, MenuSelectionManager manager)
          Implemented to be a MenuElement -- does nothing.
 void processMouseEvent(java.awt.event.MouseEvent event, MenuElement[] path, MenuSelectionManager manager)
          Implemented to be a MenuElement -- does nothing.
 void removeNotify()
          Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.
 void setBorderPainted(boolean b)
          Sets whether the border should be painted.
 void setHelpMenu(JMenu menu)
          Sets the help menu that appears when the user selects the "help" option in the menu bar.
 void setMargin(java.awt.Insets m)
          Sets the margin between the menubar's border and its menus.
 void setSelected(java.awt.Component sel)
          Sets the currently selected component, producing a a change to the selection model.
 void setSelectionModel(SingleSelectionModel model)
          Sets the model object to handle single selections.
 
Methods inherited from class javax.swing.JComponent
addAncestorListener, addPropertyChangeListener, addPropertyChangeListener, addVetoableChangeListener, computeVisibleRect, contains, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, fireVetoableChange, getActionForKeyStroke, getActionMap, getAlignmentX, getAlignmentY, getAncestorListeners, getAutoscrolls, getBorder, getBounds, getClientProperty, getComponentGraphics, getConditionForKeyStroke, getDefaultLocale, getGraphics, getHeight, getInputMap, getInputMap, getInputVerifier, getInsets, getInsets, getListeners, getLocation, getMaximumSize, getMinimumSize, getPreferredSize, getPropertyChangeListeners, getPropertyChangeListeners, getRegisteredKeyStrokes, getSize, getToolTipText, getVerifyInputWhenFocusTarget, getVetoableChangeListeners, getVisibleRect, getWidth, getX, getY, isDoubleBuffered, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isOptimizedDrawingEnabled, isPaintingTile, isPreferredSizeSet, isRequestFocusEnabled, isValidateRoot, paintChildren, paintImmediately, paintImmediately, print, printAll, printChildren, processComponentKeyEvent, processKeyEvent, processMouseMotionEvent, putClientProperty, registerKeyboardAction, registerKeyboardAction, removeAncestorListener, removePropertyChangeListener, removePropertyChangeListener, removeVetoableChangeListener, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, resetKeyboardActions, reshape, revalidate, scrollRectToVisible, setActionMap, setAlignmentX, setAlignmentY, setAutoscrolls, setBackground, setBorder, setDefaultLocale, setDoubleBuffered, setEnabled, setFont, setForeground, setInputMap, setInputVerifier, setMaximumSize, setMinimumSize, setOpaque, setPreferredSize, setRequestFocusEnabled, setToolTipText, setVerifyInputWhenFocusTarget, setVisible, unregisterKeyboardAction, update
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, areFocusTraversalKeysSet, doLayout, findComponentAt, findComponentAt, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getLayout, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicySet, list, list, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setLayout, transferFocusBackward, transferFocusDownCycle, validate, validateTree
 
Methods inherited from class java.awt.Component
addComponentListener, addFocusListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, checkImage, checkImage, coalesceEvents, contains, createImage, createImage, createVolatileImage, createVolatileImage, disableEvents, dispatchEvent, enableEvents, enableInputMethods, getBackground, getBounds, getColorModel, getComponentListeners, getCursor, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphicsConfiguration, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMouseWheelListeners, getName, getParent, getSize, getToolkit, getTreeLock, hasFocus, imageUpdate, isBackgroundSet, isCursorSet, isDisplayable, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isShowing, isValid, isVisible, list, list, list, paintAll, prepareImage, prepareImage, processComponentEvent, processFocusEvent, processInputMethodEvent, processMouseEvent, processMouseWheelEvent, removeComponentListener, removeFocusListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, repaint, repaint, repaint, setBounds, setBounds, setCursor, setFocusable, setFocusTraversalKeysEnabled, setIgnoreRepaint, setLocale, setLocation, setLocation, setName, setSize, setSize, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Constructor Detail

JMenuBar

public JMenuBar()
Creates a new menu bar.

Method Detail

paint

public final void paint(java.awt.Graphics g)
Description copied from class: JComponent
Invoked by Swing to draw components. Applications should not invoke paint directly, but should instead use the repaint method to schedule the component for redrawing.

This method actually delegates the work of painting to three protected methods: paintComponent, paintBorder, and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Subclasses can just override this method, as always.

Overrides:
paint in class JComponent
Parameters:
g - the Graphics context in which to paint
See Also:
JComponent.paintBorder(java.awt.Graphics), JComponent.paintChildren(java.awt.Graphics), JComponent.getComponentGraphics(java.awt.Graphics), JComponent.repaint(long, int, int, int, int)

getSelectionModel

public SingleSelectionModel getSelectionModel()
Returns the model object that handles single selections.

Returns:
the SingleSelectionModel property
See Also:
SingleSelectionModel

setSelectionModel

public void setSelectionModel(SingleSelectionModel model)
Sets the model object to handle single selections.

Parameters:
model - the SingleSelectionModel to use
See Also:
SingleSelectionModel

add

public JMenu add(JMenu c)
Appends the specified menu to the end of the menu bar.

Parameters:
c - the JMenu component to add
Returns:
the menu component

getMenu

public JMenu getMenu(int index)
Returns the menu at the specified position in the menu bar.

Parameters:
index - an integer giving the position in the menu bar, where 0 is the first position
Returns:
the JMenu at that position, or null if if there is no JMenu at that position (ie. if it is a JMenuItem)

getMenuCount

public int getMenuCount()
Returns the number of items in the menu bar.

Returns:
the number of items in the menu bar

setHelpMenu

public void setHelpMenu(JMenu menu)
Sets the help menu that appears when the user selects the "help" option in the menu bar. This method is not yet implemented and will throw an exception.

Parameters:
menu - the JMenu that delivers help to the user

getHelpMenu

public JMenu getHelpMenu()
Gets the help menu for the menu bar. This method is not yet implemented and will throw an exception.

Returns:
the JMenu that delivers help to the user

getComponentIndex

public int getComponentIndex(java.awt.Component c)
Returns the index of the specified component.

Parameters:
c - the Component to find
Returns:
an integer giving the component's position, where 0 is first; or -1 if it can't be found

setSelected

public void setSelected(java.awt.Component sel)
Sets the currently selected component, producing a a change to the selection model.

Parameters:
sel - the Component to select

isSelected

public boolean isSelected()
Returns true if the menu bar currently has a component selected.

Returns:
true if a selection has been made, else false

isBorderPainted

public boolean isBorderPainted()
Returns true if the menu bars border should be painted.

Returns:
true if the border should be painted, else false

setBorderPainted

public void setBorderPainted(boolean b)
Sets whether the border should be painted.

Parameters:
b - if true and border property is not null, the border is painted.
See Also:
isBorderPainted()

paintBorder

protected final void paintBorder(java.awt.Graphics g)
Paints the menubar's border if BorderPainted property is true.

Overrides:
paintBorder in class JComponent
Parameters:
g - the Graphics context to use for painting
See Also:
JComponent.paint(java.awt.Graphics), JComponent.setBorder(javax.swing.border.Border)

setMargin

public void setMargin(java.awt.Insets m)
Sets the margin between the menubar's border and its menus. Setting to null will cause the menubar to use the default margins.

Parameters:
m - an Insets object containing the margin values
See Also:
Insets

getMargin

public java.awt.Insets getMargin()
Returns the margin between the menubar's border and its menus. If there is no previous margin, it will create a default margin with zero size.

Returns:
an Insets object containing the margin values
See Also:
Insets

processMouseEvent

public void processMouseEvent(java.awt.event.MouseEvent event,
                              MenuElement[] path,
                              MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.

Specified by:
processMouseEvent in interface MenuElement
See Also:
getSubElements()

processKeyEvent

public void processKeyEvent(java.awt.event.KeyEvent e,
                            MenuElement[] path,
                            MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.

Specified by:
processKeyEvent in interface MenuElement
See Also:
getSubElements()

menuSelectionChanged

public void menuSelectionChanged(boolean isIncluded)
Implemented to be a MenuElement -- does nothing.

Specified by:
menuSelectionChanged in interface MenuElement
See Also:
getSubElements()

getSubElements

public MenuElement[] getSubElements()
Implemented to be a MenuElement -- returns the menus in this menu bar. This is the reason for implementing the MenuElement interface -- so that the menu bar can be treated the same as other menu elements.

Specified by:
getSubElements in interface MenuElement
Returns:
an array of menu items in the menu bar.

getComponent

public java.awt.Component getComponent()
Implemented to be a MenuElement. Returns this object.

Specified by:
getComponent in interface MenuElement
Returns:
the current Component (this)
See Also:
getSubElements()

paramString

protected java.lang.String paramString()
Returns a string representation of this JMenuBar. This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null.

Overrides:
paramString in class JComponent
Returns:
a string representation of this JMenuBar

processKeyBinding

protected boolean processKeyBinding(KeyStroke ks,
                                    java.awt.event.KeyEvent e,
                                    int condition,
                                    boolean pressed)
Subclassed to check all the child menus.

Overrides:
processKeyBinding in class JComponent
Parameters:
ks - the KeyStroke queried
e - the KeyEvent
condition - one of the following values:
  • JComponent.WHEN_FOCUSED
  • JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT
  • JComponent.WHEN_IN_FOCUSED_WINDOW
pressed - true if the key is pressed
Returns:
true if there was a binding to an action, and the action was enabled

addNotify

public void addNotify()
Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.

Overrides:
addNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)

removeNotify

public void removeNotify()
Overrides JComponent.removeNotify to unregister this menu bar with the current keyboard manager.

Overrides:
removeNotify in class JComponent
See Also:
JComponent.registerKeyboardAction(java.awt.event.ActionListener, java.lang.String, javax.swing.KeyStroke, int)

paintComponent

protected final void paintComponent(java.awt.Graphics g)
Description copied from class: JComponent
Calls the UI delegate's paint method, if the UI delegate is non-null. We pass the delegate a copy of the Graphics object to protect the rest of the paint code from irrevocable changes (for example, Graphics.translate).

Overrides:
paintComponent in class JComponent
Parameters:
g - the Graphics object to protect
See Also:
JComponent.paint(java.awt.Graphics), ComponentUI

paintComponents

public final void paintComponents(java.awt.Graphics g)

printComponent

protected final void printComponent(java.awt.Graphics g)
Description copied from class: JComponent
This is invoked during a printing operation. This is implemented to invoke paintComponent on the component.

Overrides:
printComponent in class JComponent
Parameters:
g - the Graphics context in which to paint
See Also:
JComponent.print(java.awt.Graphics)

printBorder

protected final void printBorder(java.awt.Graphics g)
Description copied from class: JComponent
Prints the component's border. This is implemented to invoke paintBorder on the component.

Overrides:
printBorder in class JComponent
Parameters:
g - the Graphics context in which to paint
See Also:
JComponent.print(java.awt.Graphics)

printComponents

public final void printComponents(java.awt.Graphics g)

JSR-209 (Final Release)

Java and Java 2D are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
Copyright 1993 - 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All Rights Reserved.
Use of this specification is subject to this license.