FileDocCategorySizeDatePackage
JMenuBar.javaAPI DocJava SE 6 API23020Tue Jun 10 00:26:38 BST 2008javax.swing

JMenuBar

public class JMenuBar extends JComponent implements MenuElement, Accessible
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: Swing is not thread safe. For more information see Swing's Threading Policy.

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 {@link java.beans.XMLEncoder}.

beaninfo
attribute: isContainer true description: A container for holding and displaying menus.
version
1.106 08/08/06
author
Georges Saab
author
David Karlton
author
Arnaud Weber
see
JMenu
see
JPopupMenu
see
JMenuItem

Fields Summary
private static final String
uiClassID
private transient SingleSelectionModel
selectionModel
private boolean
paintBorder
private Insets
margin
private static final boolean
TRACE
private static final boolean
VERBOSE
private static final boolean
DEBUG
Constructors Summary
public JMenuBar()
Creates a new menu bar.

  // show bad params, misc.

              
      
        super();
        setFocusTraversalKeysEnabled(false);
        setSelectionModel(new DefaultSingleSelectionModel());
        updateUI();
    
Methods Summary
public javax.swing.JMenuadd(javax.swing.JMenu c)
Appends the specified menu to the end of the menu bar.

param
c the JMenu component to add
return
the menu component

        super.add(c);
        return c;
    
public voidaddNotify()
Overrides JComponent.addNotify to register this menu bar with the current keyboard manager.

        super.addNotify();
	KeyboardManager.getCurrentManager().registerMenuBar(this);
    
public javax.accessibility.AccessibleContextgetAccessibleContext()
Gets the AccessibleContext associated with this JMenuBar. For JMenuBars, the AccessibleContext takes the form of an AccessibleJMenuBar. A new AccessibleJMenuBar instance is created if necessary.

return
an AccessibleJMenuBar that serves as the AccessibleContext of this JMenuBar

        if (accessibleContext == null) {
            accessibleContext = new AccessibleJMenuBar();
        }
        return accessibleContext;
    
public java.awt.ComponentgetComponent()
Implemented to be a MenuElement. Returns this object.

return
the current Component (this)
see
#getSubElements

        return this;
    
public java.awt.ComponentgetComponentAtIndex(int i)
Returns the component at the specified index.

param
i an integer specifying the position, where 0 is first
return
the Component at the position, or null for an invalid index
deprecated
replaced by getComponent(int i)

	
        if(i < 0 || i >= getComponentCount()) {
            return null;
        }
        return getComponent(i);
    
public intgetComponentIndex(java.awt.Component c)
Returns the index of the specified component.

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

        int ncomponents = this.getComponentCount();
        Component[] component = this.getComponents();
        for (int i = 0 ; i < ncomponents ; i++) {
            Component comp = component[i];
            if (comp == c) 
                return i;
        }
        return -1;
    
public javax.swing.JMenugetHelpMenu()
Gets the help menu for the menu bar. This method is not yet implemented and will throw an exception.

return
the JMenu that delivers help to the user

        throw new Error("getHelpMenu() not yet implemented.");
    
public java.awt.InsetsgetMargin()
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.

return
an Insets object containing the margin values
see
Insets

        if(margin == null) {
            return new Insets(0,0,0,0);
        } else {
            return margin;
        }
    
public javax.swing.JMenugetMenu(int index)
Returns the menu at the specified position in the menu bar.

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

        Component c = getComponentAtIndex(index);
        if (c instanceof JMenu) 
            return (JMenu) c;
        return null;
    
public intgetMenuCount()
Returns the number of items in the menu bar.

return
the number of items in the menu bar

        return getComponentCount();
    
public javax.swing.SingleSelectionModelgetSelectionModel()
Returns the model object that handles single selections.

return
the SingleSelectionModel property
see
SingleSelectionModel

        return selectionModel;
    
public javax.swing.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.

return
an array of menu items in the menu bar.

        MenuElement result[];
        Vector tmp = new Vector();
        int c = getComponentCount();
        int i;
        Component m;

        for(i=0 ; i < c ; i++) {
            m = getComponent(i);
            if(m instanceof MenuElement)
                tmp.addElement(m);
        }

        result = new MenuElement[tmp.size()];
        for(i=0,c=tmp.size() ; i < c ; i++) 
            result[i] = (MenuElement) tmp.elementAt(i);
        return result;
    
public javax.swing.plaf.MenuBarUIgetUI()
Returns the menubar's current UI.

see
#setUI

        return (MenuBarUI)ui;
    
public java.lang.StringgetUIClassID()
Returns the name of the L&F class that renders this component.

return
the string "MenuBarUI"
see
JComponent#getUIClassID
see
UIDefaults#getUI

        return uiClassID;
    
public booleanisBorderPainted()
Returns true if the menu bars border should be painted.

return
true if the border should be painted, else false

        return paintBorder;
    
public booleanisSelected()
Returns true if the menu bar currently has a component selected.

return
true if a selection has been made, else false

       
        return selectionModel.isSelected();
    
public voidmenuSelectionChanged(boolean isIncluded)
Implemented to be a MenuElement -- does nothing.

see
#getSubElements

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

param
g the Graphics context to use for painting
see
JComponent#paint
see
JComponent#setBorder

    
        if (isBorderPainted()) {
            super.paintBorder(g);
        }
    
protected java.lang.StringparamString()
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.

return
a string representation of this JMenuBar

	String paintBorderString = (paintBorder ?
				    "true" : "false");
	String marginString = (margin != null ?
			       margin.toString() : "");

	return super.paramString() +
	",margin=" + marginString +
	",paintBorder=" + paintBorderString;
    
static booleanprocessBindingForKeyStrokeRecursive(javax.swing.MenuElement elem, javax.swing.KeyStroke ks, java.awt.event.KeyEvent e, int condition, boolean pressed)

        if (elem == null) {
            return false;
        }

        Component c = elem.getComponent();

        if ( !(c.isVisible() || (c instanceof JPopupMenu)) || !c.isEnabled() ) {
            return false;
        }

        if (c != null && c instanceof JComponent &&
            ((JComponent)c).processKeyBinding(ks, e, condition, pressed)) {

            return true;
        }

        MenuElement[] subElements = elem.getSubElements();
        for(int i=0; i<subElements.length; i++) {
            if (processBindingForKeyStrokeRecursive(subElements[i], ks, e,
                                                    condition, pressed)) {
                return true;
                // We don't, pass along to children JMenu's
            }
        }
        return false;
    
protected booleanprocessKeyBinding(javax.swing.KeyStroke ks, java.awt.event.KeyEvent e, int condition, boolean pressed)
Subclassed to check all the child menus.

since
1.3

	// See if we have a local binding.
	boolean retValue = super.processKeyBinding(ks, e, condition, pressed);
	if (!retValue) {
            MenuElement[] subElements = getSubElements();
            for (int i=0; i<subElements.length; i++) {
                if (processBindingForKeyStrokeRecursive(
                                                        subElements[i], ks, e, condition, pressed)) {
                    return true;
                }
            }
        }
        return retValue;
    
public voidprocessKeyEvent(java.awt.event.KeyEvent e, javax.swing.MenuElement[] path, javax.swing.MenuSelectionManager manager)
Implemented to be a MenuElement -- does nothing.

see
#getSubElements

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

see
#getSubElements

    
private voidreadObject(java.io.ObjectInputStream s)
See JComponent.readObject() for information about serialization in Swing.

        s.defaultReadObject();
        Object[] kvData = (Object[])(s.readObject());

        for(int i = 0; i < kvData.length; i += 2) {
            if (kvData[i] == null) {
                break;
            }
            else if (kvData[i].equals("selectionModel")) {
                selectionModel = (SingleSelectionModel)kvData[i + 1];
            }
        }

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

        super.removeNotify();
	KeyboardManager.getCurrentManager().unregisterMenuBar(this);
    
public voidsetBorderPainted(boolean b)
Sets whether the border should be painted.

param
b if true and border property is not null, the border is painted.
see
#isBorderPainted
beaninfo
bound: true attribute: visualUpdate true description: Whether the border should be painted.

        boolean oldValue = paintBorder;
        paintBorder = b;
        firePropertyChange("borderPainted", oldValue, paintBorder);
        if (b != oldValue) {
            revalidate();
            repaint();
        }
    
public voidsetHelpMenu(javax.swing.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.

param
menu the JMenu that delivers help to the user

        throw new Error("setHelpMenu() not yet implemented.");
    
public voidsetMargin(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.

param
m an Insets object containing the margin values
see
Insets
beaninfo
bound: true attribute: visualUpdate true description: The space between the menubar's border and its contents

        Insets old = margin;
        this.margin = m;
        firePropertyChange("margin", old, m);
        if (old == null || !old.equals(m)) {
            revalidate();
            repaint();
        }
    
public voidsetSelected(java.awt.Component sel)
Sets the currently selected component, producing a a change to the selection model.

param
sel the Component to select

    
        SingleSelectionModel model = getSelectionModel();
        int index = getComponentIndex(sel);
        model.setSelectedIndex(index);
    
public voidsetSelectionModel(javax.swing.SingleSelectionModel model)
Sets the model object to handle single selections.

param
model the SingleSelectionModel to use
see
SingleSelectionModel
beaninfo
bound: true description: The selection model, recording which child is selected.

	SingleSelectionModel oldValue = selectionModel;
        this.selectionModel = model;
        firePropertyChange("selectionModel", oldValue, selectionModel);
    
public voidsetUI(javax.swing.plaf.MenuBarUI ui)
Sets the L&F object that renders this component.

param
ui the new MenuBarUI L&F object
see
UIDefaults#getUI
beaninfo
bound: true hidden: true attribute: visualUpdate true description: The UI object that implements the Component's LookAndFeel.

        super.setUI(ui);
    
public voidupdateUI()
Resets the UI property with a value from the current look and feel.

see
JComponent#updateUI

        setUI((MenuBarUI)UIManager.getUI(this));
    
private voidwriteObject(java.io.ObjectOutputStream s)

        s.defaultWriteObject();
        if (getUIClassID().equals(uiClassID)) {
            byte count = JComponent.getWriteObjCounter(this);
            JComponent.setWriteObjCounter(this, --count);
            if (count == 0 && ui != null) {
                ui.installUI(this);
            }
        }

        Object[] kvData = new Object[4];
        int n = 0;

        if (selectionModel instanceof Serializable) {
            kvData[n++] = "selectionModel";
            kvData[n++] = selectionModel;
        }

        s.writeObject(kvData);