简体   繁体   中英

Java Swing L&F native keyboard shortcuts

How do I leverage standard operating system keyboard shortcuts in a Java Swing application? I see how to add a javax.swing.JToolbar or a menu bar to my application, but it doesn't appear to be bound to de facto standard keyboard shortcuts (like Ctrl+S for Save).

Building off of other people's answers, I thought I'd share what I did in my own app...

First, I have a class variable which is declared and initialized like this:

private static int keyMask = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();

Next, in the same class, I have this method:

private static void addNewMenuItem(JMenu rootMenu, String itemName,
        int itemMnemonic, ActionListener itemActionListener) {
    JMenuItem menuItem = new JMenuItem(itemName, itemMnemonic);
    menuItem.setAccelerator(KeyStroke.getKeyStroke(itemMnemonic, keyMask)); // <-- Where I use keyMask.
    menuItem.addActionListener(itemActionListener);
    rootMenu.add(menuItem);
}

Now, all that I have to do to create a new menu is write something like:

addNewMenuItem(fileMenu, "Save...", KeyEvent.VK_S, saveListener);

As you might imagine, it's a really handy method for cleaning up code where I'm setting up a menu with dozens of items. I hope that helps someone. (I didn't go the Action route because it would require me to set up a new class for each action... that seemed like an irritating limitation to have to get around. I'm pretty sure this code is shorter than that code would be.)

You can use Toolkit.getDefaultToolkit.getMenuShortcutKeyMask() to get the correct modifier key per-platform ( Ctrl , Command , etc.), but I'm not aware of any way to find out what the "standard" shortcuts for an action are, without defining them yourself.

Something that excels a little bit more at being native, like SWT, might be better at this kind of thing, though.

Read the Swing tutorial on How to Use Actions .

An Action is basically an ActionListener with a few more properties. You can define the text, mnemonic and accelerators for the Action. Then you can use the same Action to create a JButton which you add to a toolbar or a JMenuItem which you add to a menu.

You should manually bind your keyboard shortcut to the desired menu entry. For example using the setAccelerator() method on JMenuItem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM