Swing Menus, Toolbars and Tooltips: Mnemonics, Accelerators and Popup Menus
Building menu bars, submenus, check box and radio menu items and pop-up menus in Swing; keyboard mnemonics and platform-correct accelerators; enabling items at the right moment; and toolbars and tooltips that share Action objects with the menus.
kvi5hnuCode Sprout team member11 min readOn this page
Most desktop applications put their commands into pull-down menus: a menu bar at the top of the window holds menus, each menu holds items and submenus, and choosing an item sends an event to the program. Toolbars offer the most frequent commands as buttons, and pop-up menus offer the commands that apply to the thing under the mouse. In Swing all three are built from the same pieces, and with Action objects (Article 90) one command can appear in all of them, sharing its name, icon, shortcut, tooltip and enabled state.

Building menus
Create a menu bar, add menus to it, and install it in the frame:
var menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
var editMenu = new JMenu("Edit");
menuBar.add(editMenu);
setJMenuBar puts the bar above the content pane; a menu bar is an ordinary component, so you could also put it elsewhere, but nobody does. Then add items, separators and submenus to each menu:
var pasteItem = new JMenuItem("Paste");
pasteItem.addActionListener(listener);
editMenu.add(pasteItem);
editMenu.addSeparator();
editMenu.add(optionsMenu); // a JMenu added to a JMenu becomes a submenu
Choosing an item fires an action event. There are shortcuts: editMenu.add("Paste") creates the item and returns it, so you can attach the listener to the result. Better still, add an Action:
var exitAction = new AbstractAction("Exit") {
public void actionPerformed(ActionEvent event) { System.exit(0); }
};
JMenuItem exitItem = fileMenu.add(exitAction);
The item takes its text from the action's NAME, its icon from SMALL_ICON, its mnemonic from MNEMONIC_KEY, its accelerator from ACCELERATOR_KEY, and it uses the action as its listener. It also follows the action: disabling the action disables every menu item and button made from it. insert(item, index), insertSeparator(index) and remove(item) change menus later, but use them sparingly: users are confused by menus whose contents keep changing. Prefer disabling items (see below).
Icons in menu items
JMenuItem extends AbstractButton, so menu items can have text, an icon, or both, just like buttons: new JMenuItem("Cut", cutIcon), or setIcon, or the action's SMALL_ICON. The text appears to the right of the icon; setHorizontalTextPosition(SwingConstants.LEFT) moves it to the left. Icons need not be image files: any class implementing the Icon interface works, and the demo draws its icons in code. For crisp icons on high-resolution screens, provide images at several sizes with a BaseMultiResolutionImage, or draw them, as libraries such as FlatLaf's SVG icon support do.
Check box and radio button menu items
JCheckBoxMenuItem and JRadioButtonMenuItem show a check mark or radio dot next to their text and toggle automatically when chosen. Radio button items go into a ButtonGroup, exactly like radio buttons:
var readOnlyItem = new JCheckBoxMenuItem("Read-only");
var insertItem = new JRadioButtonMenuItem("Insert", true);
var overtypeItem = new JRadioButtonMenuItem("Overtype");
var group = new ButtonGroup();
group.add(insertItem);
group.add(overtypeItem);
Often you do not need a listener: keep the items in fields and ask isSelected() when the setting matters. Add a listener only when the choice must take effect immediately.
Pop-up menus
A pop-up (context) menu floats over a component instead of hanging from the menu bar. It has no title:
var popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
The simplest way to show it is to attach it to a component:
textArea.setComponentPopupMenu(popup);
Swing then displays it when the user performs the platform's pop-up trigger: a right-click on most systems, Control-click on macOS, or the Menu key and Shift+F10 on keyboards. If you handle mouse events yourself, check event.isPopupTrigger() in both mousePressed and mouseReleased, because platforms differ about which one is the trigger (Windows uses the release, macOS and Linux the press), and then call popup.show(component, x, y) with coordinates relative to the component.
A child component inside a component with a pop-up menu does not show the parent's menu unless you call child.setInheritsPopupMenu(true). The demo found that JLabel is an exception: its UI delegate sets this property by default, so a click on a label shows its container's menu.
Keyboard mnemonics and accelerators
Experienced users want to use menus without a mouse. Swing supports two kinds of keyboard access.
A mnemonic is a letter that selects an item from a menu that is already open. It is underlined in the item's text:
var aboutItem = new JMenuItem("About", 'A'); // in the constructor
var helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H'); // menus have no constructor for it
For top-level menus, Alt plus the mnemonic opens the menu (Alt+H for Help). By default the first matching letter is underlined, ignoring case; for "Save As" with mnemonic A, call setDisplayedMnemonicIndex(5) to underline the A of "As". With actions, set the MNEMONIC_KEY and DISPLAYED_MNEMONIC_INDEX_KEY values. Pass a KeyEvent.VK_ constant or an upper-case letter; a mnemonic that does not appear in the text still works but is invisible, which helps nobody. (The macOS look and feel does not display or use menu mnemonics, following the conventions of that platform.)
An accelerator is a key combination that triggers an item without opening the menu, such as Ctrl+S for Save. It is shown at the right of the item:
openItem.setAccelerator(KeyStroke.getKeyStroke("ctrl O"));
saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));
Accelerators can be set only on menu items, not on menus. Pressing the keys fires the item's action event directly, as if the user had chosen it.
Hard-coding Ctrl is wrong on macOS, where the shortcut modifier is Command. Ask the toolkit for the right one:
int shortcut = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx(); // Ctrl or Command
saveItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, shortcut));
Some keys belong to the operating system, not to your menus: on Windows, Alt+F4 closes the active window (it arrives as a window-closing event) whether or not you have an Exit item.
macOS integration
On macOS, users expect the menu bar at the top of the screen, not inside the window. Set the system property apple.laf.useScreenMenuBar to "true" before creating any windows (or on the command line), and the JMenuBar moves there. The application menu's About, Preferences (Settings) and Quit items are reached through java.awt.Desktop: setAboutHandler, setPreferencesHandler and setQuitHandler, available on all platforms since Java 9 when isSupported(Desktop.Action.APP_ABOUT) and friends say so.
Enabling and disabling menu items
Some commands make sense only in some situations: Save is pointless for a read-only document, Paste when the clipboard is empty. Removing such items would surprise users; instead, disable them. A disabled item is grayed out and cannot be chosen:
saveAction.setEnabled(false); // disables every item and button made from the action
saveItem.setEnabled(false); // or just this item
There are two strategies. Either update the enabled state whenever the circumstances change (the document becomes read-only, the selection becomes empty), or check just before a menu opens, with a MenuListener:
fileMenu.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) { // called before the menu is displayed
saveAction.setEnabled(!readOnlyItem.isSelected());
}
public void menuDeselected(MenuEvent e) { } // after it closes
public void menuCanceled(MenuEvent e) { } // the user clicked elsewhere
});
The second strategy has a trap: an accelerator triggers an item without opening its menu, so the listener never runs and the item stays enabled. For commands with accelerators, and for actions that also appear on toolbars, update the state when it changes.
Toolbars
A toolbar is a row of buttons for the most frequently used commands. Add components or, more conveniently, actions:
var toolbar = new JToolBar("Edit tools"); // the title is shown when it floats
toolbar.add(cutAction);
toolbar.add(copyAction);
toolbar.addSeparator();
toolbar.add(new JComboBox<>(zoomLevels)); // any component may go into a toolbar
frame.add(toolbar, BorderLayout.NORTH);
add(Action) creates a JButton that shows the action's icon (hiding its text if there is an icon) and uses its SHORT_DESCRIPTION as tooltip. Use new JToolBar(SwingConstants.VERTICAL) for a vertical bar.
By default the user can drag a toolbar by its handle to another edge of the window, or out of the window into a separate small frame; closing that frame returns the toolbar. Dragging to an edge works only when the toolbar's container uses a BorderLayout (or another layout manager with north, east, south and west constraints), with the toolbar the only component on its edge. Many applications switch the feature off with setFloatable(false); setRollover(true) gives the flat, highlight-on-hover buttons common today.
Tooltips
Toolbar icons are often cryptic. A tooltip explains a component when the mouse rests over it for a moment:
exitButton.setToolTipText("Exit the program");
exitAction.putValue(Action.SHORT_DESCRIPTION, "Exit the program"); // for buttons made from an action
Any JComponent can have a tooltip, and tooltips accept HTML for several lines or emphasis. The shared ToolTipManager controls the timing: by default a tooltip appears after 750 milliseconds, disappears after 4 seconds, and appears immediately when moving to a neighboring component within half a second. ToolTipManager.sharedInstance().setDismissDelay(...) changes that globally, and setEnabled(false) turns tooltips off. Tooltips are not accessible to keyboard-only users in every look and feel, so do not hide essential information in them.
A small editor
This program puts it together: File and Edit menus with mnemonics, accelerators using the platform's shortcut key, a submenu with check box items, a toolbar and a pop-up menu sharing the text component's own cut, copy and paste actions (from DefaultEditorKit), and a menu listener. The read-only option disables Save immediately, because Save has an accelerator.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
import javax.swing.text.DefaultEditorKit;
public final class NotepadFrame extends JFrame {
private static final long serialVersionUID = 1L;
// Ctrl on Windows and Linux, Command on macOS
private static final int SHORTCUT = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
private final JTextArea text = new JTextArea(15, 50);
private final JLabel status = new JLabel(" ");
private final JCheckBoxMenuItem readOnlyItem = new JCheckBoxMenuItem("Read-only");
private final AbstractAction saveAction = new AbstractAction("Save") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) { status.setText("Saved " + text.getText().length() + " characters"); }
};
private final AbstractAction clearAction = new AbstractAction("Clear") {
private static final long serialVersionUID = 1L;
public void actionPerformed(ActionEvent e) { text.setText(""); }
};
public NotepadFrame() {
super("Notepad");
configure(saveAction, KeyEvent.VK_S, KeyStroke.getKeyStroke(KeyEvent.VK_S, SHORTCUT), "Save the text");
configure(clearAction, KeyEvent.VK_L, null, "Remove all text");
// the text component's own editing actions, renamed for the menu
Action cut = named(new DefaultEditorKit.CutAction(), "Cut", KeyEvent.VK_T, "Cut the selection");
Action copy = named(new DefaultEditorKit.CopyAction(), "Copy", KeyEvent.VK_C, "Copy the selection");
Action paste = named(new DefaultEditorKit.PasteAction(), "Paste", KeyEvent.VK_P, "Paste");
var fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
fileMenu.add(saveAction);
fileMenu.add(clearAction);
fileMenu.addSeparator();
JMenuItem exit = fileMenu.add("Exit");
exit.setMnemonic('x');
exit.addActionListener(_ -> dispose());
fileMenu.addMenuListener(new MenuListener() { // last-moment check before opening
public void menuSelected(MenuEvent e) { clearAction.setEnabled(!text.getText().isEmpty() && text.isEditable()); }
public void menuDeselected(MenuEvent e) { }
public void menuCanceled(MenuEvent e) { }
});
var wrapItem = new JCheckBoxMenuItem("Word wrap");
wrapItem.addActionListener(_ -> {
text.setLineWrap(wrapItem.isSelected());
text.setWrapStyleWord(true);
});
// read-only also disables Save, which has an accelerator, so update it right away
readOnlyItem.addActionListener(_ -> {
boolean editable = !readOnlyItem.isSelected();
text.setEditable(editable);
saveAction.setEnabled(editable);
});
var editMenu = new JMenu("Edit");
editMenu.setMnemonic('E');
editMenu.add(cut).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, SHORTCUT));
editMenu.add(copy).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, SHORTCUT));
editMenu.add(paste).setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, SHORTCUT));
editMenu.addSeparator();
var options = new JMenu("Options");
options.setMnemonic('O');
options.add(wrapItem);
options.add(readOnlyItem);
editMenu.add(options);
var menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(editMenu);
setJMenuBar(menuBar);
var toolbar = new JToolBar("Tools");
toolbar.add(saveAction);
toolbar.addSeparator();
toolbar.add(cut);
toolbar.add(copy);
toolbar.add(paste);
add(toolbar, BorderLayout.NORTH);
var popup = new JPopupMenu();
popup.add(cut);
popup.add(copy);
popup.add(paste);
text.setComponentPopupMenu(popup);
add(new JScrollPane(text), BorderLayout.CENTER);
add(status, BorderLayout.SOUTH);
pack();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationByPlatform(true);
}
private static void configure(Action a, int mnemonic, KeyStroke accelerator, String tip) {
a.putValue(Action.MNEMONIC_KEY, mnemonic);
a.putValue(Action.SHORT_DESCRIPTION, tip);
if (accelerator != null) a.putValue(Action.ACCELERATOR_KEY, accelerator);
}
private static Action named(Action a, String name, int mnemonic, String tip) {
a.putValue(Action.NAME, name);
configure(a, mnemonic, null, tip);
return a;
}
public static void main(String[] args) {
System.setProperty("apple.laf.useScreenMenuBar", "true"); // macOS: menu bar at the top of the screen
EventQueue.invokeLater(() -> new NotepadFrame().setVisible(true));
}
}
The program
The demo builds a menu bar from actions without displaying it, prints its structure with mnemonics and accelerators, chooses items with doClick, simulates opening a menu, and examines a toolbar, a pop-up menu and tooltip settings.
import java.awt.Component;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;
public class Solution {
static final List<String> log = new ArrayList<>();
/** An action that records its name when performed. */
static class LoggingAction extends AbstractAction {
private static final long serialVersionUID = 1L;
LoggingAction(String name, String tip) {
super(name);
putValue(SHORT_DESCRIPTION, tip);
}
@Override public void actionPerformed(ActionEvent e) {
log.add(getValue(NAME) + " (from a " + (e.getSource() instanceof JMenuItem ? "menu item" : "button") + ")");
}
}
/** A tiny square icon, drawn in code so the demo needs no image files. */
record SquareIcon(int size) implements Icon {
public void paintIcon(Component c, Graphics g, int x, int y) { g.fillRect(x, y, size, size); }
public int getIconWidth() { return size; }
public int getIconHeight() { return size; }
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "true");
SwingUtilities.invokeAndWait(Solution::run);
}
static void run() {
var newAction = new LoggingAction("New", "Create a document");
var openAction = new LoggingAction("Open", "Open a document");
var saveAction = new LoggingAction("Save", "Save the document");
var saveAsAction = new LoggingAction("Save As", "Save under a new name");
var cutAction = new LoggingAction("Cut", "Cut the selection");
var copyAction = new LoggingAction("Copy", "Copy the selection");
var pasteAction = new LoggingAction("Paste", "Paste the clipboard");
for (var a : List.of(cutAction, copyAction, pasteAction)) a.putValue(Action.SMALL_ICON, new SquareIcon(16));
openAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke("ctrl O"));
saveAction.putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_DOWN_MASK));
saveAsAction.putValue(Action.MNEMONIC_KEY, KeyEvent.VK_A);
saveAsAction.putValue(Action.DISPLAYED_MNEMONIC_INDEX_KEY, 5); // underline the A of "As"
var fileMenu = new JMenu("File");
fileMenu.setMnemonic('F');
fileMenu.add(newAction);
fileMenu.add(openAction);
fileMenu.addSeparator();
JMenuItem saveItem = fileMenu.add(saveAction);
fileMenu.add(saveAsAction);
var readOnly = new JCheckBoxMenuItem("Read-only");
var insert = new JRadioButtonMenuItem("Insert", true);
var overtype = new JRadioButtonMenuItem("Overtype");
var group = new ButtonGroup();
group.add(insert);
group.add(overtype);
var options = new JMenu("Options");
options.add(readOnly);
options.addSeparator();
options.add(insert);
options.add(overtype);
var editMenu = new JMenu("Edit");
editMenu.setMnemonic('E');
editMenu.add(cutAction);
editMenu.add(copyAction);
editMenu.add(pasteAction);
editMenu.addSeparator();
editMenu.add(options); // a submenu is just a menu inside a menu
var helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.add(new JMenuItem("About", 'A'));
var menuBar = new JMenuBar();
menuBar.add(fileMenu);
menuBar.add(editMenu);
menuBar.add(helpMenu);
System.out.println("== The menu tree ==");
for (int i = 0; i < menuBar.getMenuCount(); i++) print(menuBar.getMenu(i), "");
System.out.println();
System.out.println("== Menu items fire action events ==");
saveItem.doClick(0);
readOnly.doClick(0);
overtype.doClick(0);
log.forEach(s -> System.out.println(" " + s));
System.out.println("read-only " + readOnly.isSelected() + ", insert " + insert.isSelected()
+ ", overtype " + overtype.isSelected());
System.out.println();
System.out.println("== Enable items just before the menu opens ==");
fileMenu.addMenuListener(new MenuListener() {
public void menuSelected(MenuEvent e) {
boolean writable = !readOnly.isSelected();
saveAction.setEnabled(writable);
saveAsAction.setEnabled(writable);
System.out.println(" menuSelected: save enabled = " + writable);
}
public void menuDeselected(MenuEvent e) { System.out.println(" menuDeselected"); }
public void menuCanceled(MenuEvent e) { }
});
fileMenu.setSelected(true); // what the UI does when the user opens it
fileMenu.setSelected(false);
log.clear();
saveItem.doClick(0);
System.out.println("clicking disabled Save item: " + (log.isEmpty() ? "nothing happens" : log));
System.out.println();
System.out.println("== A toolbar shares the actions ==");
var toolbar = new JToolBar("Edit tools");
JButton cutButton = toolbar.add(cutAction);
toolbar.add(copyAction);
toolbar.addSeparator();
toolbar.add(pasteAction);
toolbar.add(new JComboBox<>(new String[] {"100%", "150%"}));
for (Component c : toolbar.getComponents()) {
if (c instanceof JButton b)
System.out.printf(" button: icon %s, text shown %-5s tooltip \"%s\"%n",
b.getIcon() != null ? "yes" : "no", !b.getHideActionText() + ",", b.getToolTipText());
else System.out.println(" " + c.getClass().getSimpleName());
}
cutAction.setEnabled(false);
JMenuItem cutItem = editMenu.getItem(0);
System.out.println("cut action disabled -> button enabled " + cutButton.isEnabled()
+ ", menu item enabled " + cutItem.isEnabled());
System.out.println("floatable " + toolbar.isFloatable() + ", orientation horizontal "
+ (toolbar.getOrientation() == SwingConstants.HORIZONTAL));
System.out.println();
System.out.println("== Pop-up menus and tooltips ==");
var popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
var panel = new JPanel();
panel.setComponentPopupMenu(popup);
var child = new JButton("inside the panel");
panel.add(child);
System.out.println("child pop-up before inheriting: " + child.getComponentPopupMenu());
System.out.println("a JLabel inherits by default: " + new JLabel("label").getInheritsPopupMenu());
child.setInheritsPopupMenu(true);
System.out.println("child pop-up after inheriting: "
+ (child.getComponentPopupMenu() == popup ? "the panel's menu (" + popup.getComponentCount() + " items)" : "?"));
var help = new JButton("?");
help.setToolTipText("<html>Show <b>help</b></html>");
System.out.println("tooltip: " + help.getToolTipText());
var tips = ToolTipManager.sharedInstance();
System.out.println("tooltip delays: initial " + tips.getInitialDelay() + " ms, dismiss "
+ tips.getDismissDelay() + " ms, reshow " + tips.getReshowDelay() + " ms");
}
static void print(JMenuItem item, String indent) {
StringBuilder line = new StringBuilder(indent).append(item.getText());
int m = item.getMnemonic();
if (m != 0) {
int index = item.getDisplayedMnemonicIndex();
line.append(" [mnemonic ").append((char) m).append(", underlined at ").append(index).append("]");
}
KeyStroke k = item instanceof JMenu ? null : item.getAccelerator();
if (k != null) line.append(" [accelerator ").append(k).append("]");
if (item instanceof JCheckBoxMenuItem) line.append(" (check box)");
if (item instanceof JRadioButtonMenuItem) line.append(" (radio)");
if (item.getIcon() != null) line.append(" (icon)");
System.out.println(line);
if (item instanceof JMenu menu) {
for (int i = 0; i < menu.getItemCount(); i++) {
JMenuItem child = menu.getItem(i); // null for a separator
if (child == null) System.out.println(indent + " ----");
else print(child, indent + " ");
}
}
}
}
== The menu tree ==
File [mnemonic F, underlined at 0]
New
Open [accelerator ctrl pressed O]
----
Save [accelerator ctrl pressed S]
Save As [mnemonic A, underlined at 5]
Edit [mnemonic E, underlined at 0]
Cut (icon)
Copy (icon)
Paste (icon)
----
Options
Read-only (check box)
----
Insert (radio)
Overtype (radio)
Help [mnemonic H, underlined at 0]
About [mnemonic A, underlined at 0]
== Menu items fire action events ==
Save (from a menu item)
read-only true, insert false, overtype true
== Enable items just before the menu opens ==
menuSelected: save enabled = false
menuDeselected
clicking disabled Save item: nothing happens
== A toolbar shares the actions ==
button: icon yes, text shown false, tooltip "Cut the selection"
button: icon yes, text shown false, tooltip "Copy the selection"
Separator
button: icon yes, text shown false, tooltip "Paste the clipboard"
JComboBox
cut action disabled -> button enabled false, menu item enabled false
floatable true, orientation horizontal true
== Pop-up menus and tooltips ==
child pop-up before inheriting: null
a JLabel inherits by default: true
child pop-up after inheriting: the panel's menu (3 items)
tooltip: <html>Show <b>help</b></html>
tooltip delays: initial 750 ms, dismiss 4000 ms, reshow 500 ms
Points to notice:
getItem(i)returnsnullfor separators, which the printout shows as dashes.- The accelerators came from the actions'
ACCELERATOR_KEYvalues;KeyStroke.toStringdescribes them in the same syntax thatgetKeyStroke(String)accepts, plus the event type ("pressed"). setSelected(true)on the File menu, which the UI delegate calls when the user opens it, ran the menu listener; the disabled Save item then ignoreddoClick.- Disabling the cut action disabled both the toolbar button and the menu item created from it.
Common questions
Why doesn't my accelerator work?
The menu bar must be installed in a frame (setJMenuBar) that is active, the item must be enabled, and the key must not be consumed by the focused component (text fields use Ctrl+C, Ctrl+V and others themselves). Check that you used the platform's shortcut mask on macOS.
How do I show a "Recent files" submenu?
Keep the list in Preferences (article 92), and rebuild the submenu's items from it in a MenuListener.menuSelected, or whenever a file is opened. Disable the submenu when the list is empty.
How do I add an icon that looks sharp on high-DPI screens?
Use SVG icons through a library (FlatLaf's FlatSVGIcon), or supply several resolutions with BaseMultiResolutionImage and wrap it in an ImageIcon. Icons drawn in code with Graphics2D scale automatically.
Can a menu item have both a mnemonic and an accelerator? Yes, and it should. The mnemonic works while the menu is open; the accelerator works anywhere in the window.
How do I put the menu bar at the top of the screen on macOS?
Set System.setProperty("apple.laf.useScreenMenuBar", "true") before creating any Swing components, or pass -Dapple.laf.useScreenMenuBar=true. Use Desktop.getDesktop().setAboutHandler(...) and setQuitHandler(...) for the application menu.
API reference
| Class / method | Purpose |
|---|---|
JMenuBar, add(menu), JFrame.setJMenuBar | Menu bar. |
JMenu(label), add(item), add(String), add(Action), addSeparator, insert, insertSeparator, remove, getItem, getItemCount | Menus. |
JMenuItem(label), JMenuItem(label, icon), JMenuItem(label, mnemonic), JMenuItem(action), setAccelerator | Menu items. |
JCheckBoxMenuItem(label, state), JRadioButtonMenuItem(label, state), isSelected, setSelected | Toggling items. |
JPopupMenu, show(component, x, y), JComponent.setComponentPopupMenu, setInheritsPopupMenu, MouseEvent.isPopupTrigger | Pop-up menus. |
AbstractButton.setMnemonic, setDisplayedMnemonicIndex, setHorizontalTextPosition, setAction | Mnemonics, layout of text and icon. |
KeyStroke.getKeyStroke(String), getKeyStroke(keyCode, modifiers), Toolkit.getMenuShortcutKeyMaskEx | Accelerators. |
Action.NAME, SMALL_ICON, SHORT_DESCRIPTION, MNEMONIC_KEY, DISPLAYED_MNEMONIC_INDEX_KEY, ACCELERATOR_KEY | Action properties used by items and buttons. |
MenuListener.menuSelected/menuDeselected/menuCanceled, JMenu.addMenuListener | Reacting to menus opening. |
JToolBar(title, orientation), add(Action), addSeparator, setFloatable, setRollover | Toolbars. |
JComponent.setToolTipText, ToolTipManager.sharedInstance, setInitialDelay, setDismissDelay | Tooltips. |
Desktop.setAboutHandler, setPreferencesHandler, setQuitHandler | macOS application menu. |
Summary
- A
JMenuBarholdsJMenus, which holdJMenuItems, separators and submenus; items fire action events. Build items fromActions so that menus, toolbars and pop-ups share text, icon, shortcut, tooltip and enabled state. - Check box and radio button menu items toggle themselves; radio items need a
ButtonGroup. - Attach pop-up menus with
setComponentPopupMenu; the trigger differs by platform, so let Swing detect it. - Mnemonics select items in open menus; accelerators fire items directly. Use
getMenuShortcutKeyMaskExso that shortcuts use Command on macOS. - Disable rather than remove inapplicable items. Enabling in
menuSelecteddoes not cover accelerators. - Toolbars made from actions show icons with tooltips; they can float unless
setFloatable(false). Any component can have a tooltip.
Practice Questions
1. What is the difference between a mnemonic and an accelerator?
A mnemonic is a letter, underlined in the item's text, that selects the item when its menu is already open (or, with Alt, opens a top-level menu). An accelerator is a key combination such as Ctrl+S that triggers a menu item directly, without opening any menu; it is displayed at the right side of the item. Menus can have mnemonics but not accelerators.
2. A program disables its Save item in menuSelected when the document is read-only. A user still saves a read-only document. How?
With the accelerator (for example Ctrl+S). An accelerator fires the item's action without opening the menu, so menuSelected never runs and the item, or its action, is still enabled. Update the enabled state when the read-only setting changes, instead of just before the menu opens.
3. Why should you write KeyStroke.getKeyStroke(KeyEvent.VK_S, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx()) instead of KeyStroke.getKeyStroke("ctrl S")?
Because the standard shortcut modifier differs by platform: Ctrl on Windows and Linux, Command on macOS. The toolkit method returns the correct modifier mask, so shortcuts feel native everywhere. On macOS, a hard-coded Ctrl would conflict with the users' habits and with system shortcuts.
4. A JPanel has a pop-up menu set with setComponentPopupMenu. Right-clicking a JButton inside the panel shows nothing, but right-clicking a JLabel inside it shows the menu. Explain.
A child component uses its parent's pop-up menu only if its inheritsPopupMenu property is true. The label's UI delegate sets that property by default, whereas a button does not. Call button.setInheritsPopupMenu(true) or give the button its own pop-up menu.
5. You add the same Action to a menu, a toolbar and a pop-up menu. What happens to the three components when you call action.setEnabled(false), and why?
All three components created from the action become disabled. Each component registers as a property change listener of its action and updates its enabled state (and text, icon, tooltip) when the action's properties change. That is the main reason to build menus and toolbars from actions.
Previous: Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
Related reading
- Swing Choice Components: Check Boxes, Radio Buttons, Borders, Combo Boxes and Sliders
- Swing Text Components: Text Fields, Labels, Password Fields and Text Areas
- Swing Layout Managers and MVC: FlowLayout, BorderLayout and GridLayout
- The Java Preferences API: Storing User Settings
- Mouse Events and the AWT Event Hierarchy in Java

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.