Menus Core Java

We started this chapter by introducing the most common components that you might want to place into a window, such as various kinds of buttons, text fields, and combo boxes. Swing also supports another type of user interface element, the pull-down menus that are familiar from GUI applications.

A menu bar on top of the window contains the names of the pull-down menus. Clicking on a name opens the menu containing menu items and submenus. When the user clicks on a menu item, all menus are closed and a message is sent to the program. a typical menu with a submenu.

A menu with a submenu

A menu with a submenu

Menu Building

Building menus is straightforward. You first create a menu bar:

A menu bar is just a component that you can add anywhere you like. Normally, you want it to appear at the top of a frame. You can add it there with the set JMenuBar method:

You add menu items, separators, and submenus to the menu object:

You can see separators below the “Paste” and “Read-only” menu items. When the user selects a menu, an action event is triggered. You need to install an action listener for each menu item:

The method JMenu.add(String s) conveniently adds a menu item to the end of a menu. For example:

The add method returns the created menu item, so you can capture it and then add the listener, as follows:

It often happens that menu items trigger commands that can also be activated throughother user interface elements such as toolbar buttons. In Chapter 8, you saw how to specify commands through Action objects. You define a class that implements the Action interface, usually by extending the AbstractAction convenience class. You specify the menu item label in the constructor of the AbstractAction object, and you override the actionPerformed method to hold the menu action handler. For example:

You can then add the action to the menu:

This command adds a menu item to the menu, using the action name. The action object becomes its listener. This is just a convenient shortcut for

  • JMenu(String label)
    constructs a menu with the given label.
  • JMenuItem add(JMenuItem item)
    adds a menu item (or a menu).
  • JMenuItem add(String label)
    adds a menu item with the given label to this menu and returns the item.
  • JMenuItem add(Action a)
    adds a menu item with the given action to this menu and returns the item.
  • void addSeparator()
    adds a separator line to the menu.
  • JMenuItem insert(JMenuItem menu, int index)
    adds a new menu item (or submenu) to the menu at a specific index.
  • JMenuItem insert(Action a, int index)
    adds a new menu item with the given action at a specific index.
  • void insertSeparator(int index)
    adds a separator to the menu.
  • void remove(int index)
  • void remove(JMenuItem item)
    removes a specific item from the menu.
  • JMenuItem(String label)
    constructs a menu item with a given label.
  • JMenuItem(Action a)
    constructs a menu item for the given action.
  • void setAction(Action a)
    sets the action for this button or menu item.
  • void setJMenuBar(JMenuBar menubar)
    sets the menu bar for this frame.

Icons in Menu Items

Menu items are very similar to buttons. In fact, the JMenuItem class extends the Abstract Button class. Just like buttons, menus can have just a text label, just an icon, or both. You can specify the icon with the JMenuItem(String, Icon) or JMenuItem(Icon) constructor, or you can set it with the setIcon method that the JMenuItem class inherits from the AbstractButton class.

Here is an example:

Inbelow, you can see icons next to several menu items. By default, the menu item text is placed to the right of the icon. If you prefer the text to be placed on the left, call the setHorizontalTextPosition method that the JMenu Item class inherits from the AbstractButton class. For example, the call cutItem .set Horizontal Text Position (Swing Constants .LEFT); moves the menu item text to the left of the icon.

You can also add an icon to an action:

Whenever you construct a menu item out of an action, the Action.NAME value becomes the text of the menu item and the Action.SMALL_ICON value becomes the icon.

Alternatively, you can set the icon in the AbstractAction constructor:

  • JMenuItem(String label, Icon icon)
    constructs a menu item with the given label and icon.
  • void setHorizontalTextPosition(int pos)
    sets the horizontal position of the text relative to the icon.
  • AbstractAction(String name, Icon smallIcon)
    constructs an abstract action with the given name and icon.

Checkbox and Radio Button Menu Items

Checkbox and radio button menu items display a checkbox or radio button next to the name. When the user selects the menu item, the item automatically toggles between checked and unchecked.

Apart from the button decoration, you treat these menu items just as you would any others. For example, here is how you create a checkbox menu item:

The radio button menu items work just like regular radio buttons. You must add them to a button group. When one of the buttons in a group is selected, all others are automatically deselected.

With these menu items, you don’t necessarily want to be notified at the exact moment the user selects the item. Instead, you can simply use the isSelected method to test the current state of the menu item. (Of course, that means that you should keep a reference to the menu item stored in an instance field.) Use the setSelected method to set the state.

  • JCheckBoxMenuItem(String label)
    constructs the checkbox menu item with the given label.
  • JCheckBoxMenuItem(String label, boolean state)

constructs the checkbox menu item with the given label and the given initial state (true is checked).

  • JRadioButtonMenuItem(String label)
    constructs the radio button menu item with the given label.
  • JRadioButtonMenuItem(String label, boolean state)
    constructs the radio button menu item with the given label and the given initial state (true is checked).
  • boolean isSelected()
  • void setSelected(boolean state)

gets or sets the selection state of this item (true is checked).

Pop-Up Menus

A pop-up menu is a menu that is not attached to a menu bar but that floats somewhere.

A pop-up menu

A pop-up menu

You create a pop-up menu similarly to the way you create a regular menu, but a pop-up menu has no title.

Unlike the regular menu bar that is always shown at the top of the frame, you must explicitly display a pop-up menu by using the show method. You specify the parent component and the location of the pop-up, using the coordinate system of the parent. For example:

Usually you write code to pop up a menu when the user clicks a particular mouse button, the so-called pop-up trigger. In Windows and Linux, the pop-up trigger is the nonprimary (usually, the right) mouse button. To pop up a menu when the user clicks on a component, using the pop-up trigger, simply call the method component.set Component PopupMenu (popup);

Very occasionally, you may place a component inside another component that has a pop-up menu. The child component can inherit the parent component’s pop-up menu by calling

These methods were added in Java SE 5.0 to insulate programmers from system dependencies with pop-up menus. Before Java SE 5.0, you had to install a mouse listener and add the following code to both the mousePressed and the mouseReleased listener methods:

Some systems trigger pop-ups when the mouse button goes down, others when the mouse button goes up.

  • void show(Component c, int x, int y)
    shows the pop-up menu.
  • boolean isPopupTrigger(MouseEvent event)
    returns true if the mouse event is the pop-up menu trigger.
  • boolean isPopupTrigger()
    returns true if this mouse event is the pop-up menu trigger.
  • JPopupMenu getComponentPopupMenu()
  • void setComponentPopupMenu(JPopupMenu popup)
    gets or sets the pop-up menu for this component.
  • boolean getInheritsPopupMenu()
  • void setInheritsPopupMenu(boolean b)
    gets or sets the inheritsPopupMenu property. If the property is set and thiscomponent’s pop-up menu is null, it uses its parent’s pop-up menu.

Keyboard Mnemonics and Accelerators

It is a real convenience for the experienced user to select menu items by keyboard mnemonics. You can specify keyboard mnemonics for menu items by specifying a mnemonic letter in the menu item constructor:

The keyboard mnemonic is displayed automatically in the menu, with the mnemonic letter underlined. For example, in the item defined in the last example, the label will be displayed as “About” with an underlined letter “A”. When the menu is displayed, the user just needs to press the A key, and the menu item is selected. (If the mnemonic letter is not part of the menu string, then typing it still selects the item, but the mnemonic is not displayed in the menu. Naturally, such invisible mnemonics are of dubious utility.)

Sometimes, you don’t want to underline the first letter of the menu item that matches the mnemonic. For example, if you have a mnemonic “A” for the menu item “Save As,” then it makes more sense to underline the second “A” (Save As). As of Java SE 1.4, you can specify which character you want to have underlined; call the set Display edMnemonic Index method. If you have an Action object, you can add the mnemonic as the value of the Action .MNEMONIC _KEY key, as follows:

Keyboard mnemonics

Keyboard mnemonics

You can supply a mnemonic letter only in the constructor of a menu item, not in the constructor for a menu. Instead, to attach a mnemonic to a menu, you call the setMnemonic method:

To select a top-level menu from the menu bar, you press the ALT key together with the mnemonic letter. For example, you press ALT+H to select the Help menu from the menu bar.

Keyboard mnemonics let you select a submenu or menu item from the currently open menu. In contrast, accelerators are keyboard shortcuts that let you select menu items without ever opening a menu. For example, many programs attach the accelerators CTRL+O and CTRL+S to the Open and Save items in the File menu. You use the setAccelerator method to attach an accelerator key to a menu item. The setAccelerator method takes an object of type Keystroke. For example, the following call attaches the accelerator CTRL+O to the openItem menu item:

When the user presses the accelerator key combination, this automatically selects the menu option and fires an action event, as if the user had selected the menu option manually.

You can attach accelerators only to menu items, not to menus. Accelerator keys don’t actually open the menu. Instead, they directly fire the action event that is associated with a menu.

Conceptually, adding an accelerator to a menu item is similar to the technique of adding an accelerator to a Swing component. However, when the accelerator is added to a menu item, the key combination is automatically displayed in the menu.



  • JMenuItem(String label, int mnemonic)
    constructs a menu item with a given label and mnemonic.
  • void setAccelerator(KeyStroke k)
    sets the keystroke k as accelerator for this menu item. The accelerator key is displayed next to the label.
  • void setMnemonic(int mnemonic)
    sets the mnemonic character for the button. This character will be underlined in the label.
  • void setDisplayedMnemonicIndex(int index) 1.4
    sets the index of the character to be underlined in the button text. Use this method if you don’t want the first occurrence of the mnemonic character to be underlined.

Enabling and Disabling Menu Items

Occasionally, a particular menu item should be selected only in certain contexts. For example, when a document is opened for reading only, then the Save menu item is not meaningful. Of course, we could remove the item from the menu with the JMenu.remove method, but users would react with some surprise to menus whose content keeps changing. Instead, it is better to deactivate the menu items that lead to temporarily inappropriate commands. A deactivated menu item is shown in gray, and it cannot be selected.

To enable or disable a menu item, use the setEnabled method:

There are two strategies for enabling and disabling menu items. Each time circumstances change, you can call setEnabled on the relevant menu items or actions. For example, as soon as a document has been set to read-only mode, you can locate the Save and Save As menu items and disable them. Alternatively, you can disable items just before displaying the menu.

To do this, you must register a listener for the “menu selected” event. The javax .swing .event package defines a MenuListener interface with three methods:

The menuSelected method is called before the menu is displayed. It can therefore be used to disable or enable menu items. The following code shows how to disable the Save and Save As actions whenever the Read Only checkbox menu item is selected:

Disabled menu items

Disabled menu items

  • void setEnabled(boolean b)
    enables or disables the menu item.
  • void menuSelected(MenuEvent e)
    is called when the menu has been selected, before it is opened.
  • void menuDeselected(MenuEvent e)
    is called when the menu has been deselected, after it has been closed.
  • void menuCanceled(MenuEvent e)
    is called when the menu has been canceled, for example, by a user clicking outside the menu.


A toolbar is a button bar that gives quick access to the most commonly used commands in a program .

A toolbar

A toolbar

What makes toolbars special is that you can move them elsewhere. You can drag the toolbar to one of the four borders of the frame. When you release the mouse button, the toolbar is dropped into the new location.

Dragging the toolbar

Dragging the toolbar

The toolbar has been dragged to another border

The toolbar has been dragged to another border

The toolbar can even be completely detached from the frame. A detached toolbar is contained in its own frame. When you close the frame containing a detached toolbar, the toolbar jumps back into the original frame.

Detaching the toolbar

Detaching the toolbar

Toolbars are straightforward to program. You add components into the toolbar:

The JToolBar class also has a method to add an Action object. Simply populate the toolbar with Action objects, like this:

For example has a separator between the third and fourth button. Then, you add the toolbar to the frame.

You can also specify a title for the toolbar that appears when the toolbar is undocked:

By default, toolbars are initially horizontal. To have a toolbar start out as vertical, use

Buttons are the most common components inside toolbars. But there is no restriction on the components that you can add to a toolbar. For example, you can add a combo box to a toolbar.


A disadvantage of toolbars is that users are often mystified by the meanings of the tiny icons in toolbars. To solve this problem, user interface designers invented tooltips. A tooltip is activated when the cursor rests for a moment over a button. The tooltip text is displayed inside a colored rectangle. When the user moves the mouse away, the tooltip is removed.

A tooltip

A tooltip

In Swing, you can add tooltips to any JComponent simply by calling the setToolTipText method:

Alternatively, if you use Action objects, you associate the tooltip with the SHORT_DESCRIPTION key.

javax.swing.JToolBar 1.2

  • JToolBar()
  • JToolBar(String titleString)
  • JToolBar(int orientation)
  • JToolBar(String titleString, int orientation)
    constructs a toolbar with the given title string and orientation. orientation is one of Swing Constants .HORIZONTAL (the default) and Swing Constants .VERTICAL.
  • JButton add(Action a)
    constructs a new button inside the toolbar with name, icon, short description, and action callback from the given action, and adds the button to the end of the toolbar.
  • void addSeparator()
    adds a separator to the end of the toolbar.
  • void setToolTipText(String text)
    sets the text that should be displayed as a tooltip when the mouse hovers over the component.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics