开发者

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 sta开发者_运维技巧ndard keyboard shortcuts (like Ctrl+S for Save).


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.


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.)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜