Java example: JMenuBar + KeyStroke + AbstractAction

As a brief note, here’s some source code that I used to create a JMenuBar in a Java application. First, I defined some fields in my main class:

private static final KeyStroke fileOpenKeystroke = KeyStroke.getKeyStroke(KeyEvent.VK_O, Event.META_MASK);
private Action fileOpenAction;
private JMenuBar menuBar;

Later in the same class I defined this method:

private JMenuBar createMenuBar() {
    JMenuBar menuBar = new JMenuBar();

    // File menu
    JMenu fileMenu = new JMenu("File");
    fileOpenAction = new FileOpenAction(this, "Open", fileOpenKeystroke.getKeyCode());
    fileMenu.add(new JMenuItem(fileOpenAction));

    // add File menu to menubar
    menuBar.add(fileMenu);

    return menuBar;
}

That code relies on a FileOpenAction, which looks like this:

import utils.GuiUtils;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;

class FileOpenAction extends AbstractAction {

    MainController controller;

    public FileOpenAction(final MainController controller, String name, Integer mnemonic) {
        super(name, null);
        putValue(MNEMONIC_KEY, mnemonic);
        this.controller = controller;
    }

    public void actionPerformed(ActionEvent e) {
        GuiUtils.handleSelectDirectoryRequest(controller.getPrefs(), MainController.LAST_USED_DIR);
    }

}

Some of that code can be rearranged, but those are the basic steps needed to create a JMenuBar that uses a KeyStroke and AbstractAction.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.