Как привязать команду-? в качестве ускорителя поворота для меню справки?

Стандартная комбинация клавиш для справки - command - ? на Mac. Как привязать эту комбинацию клавиш к пункту меню.

Примечание. Поскольку у наших пользователей разные раскладки клавиатуры, я ищу решение, которое не требует знания о том, какая клавиша "?" расположен на.

Использование KeyStroke.getKeyStroke (String) , что написано в javadoc;

Parses a string and returns a `KeyStroke`. The string must have the following syntax:

<modifiers>* (<typedID> | <pressedReleasedID>)

modifiers := shift | control | ctrl | meta | alt | button1 | button2 | button3
typedID := typed <typedKey>
typedKey := string of length 1 giving Unicode character.
pressedReleasedID := (pressed | released) key
key := KeyEvent key code name, i.e. the name following "VK_".

У меня есть пример кода:

import javax.swing.*;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

public class HelpShortcut extends JFrame {

    public HelpShortcut(){
        // A few keystrokes to experiment with
        //KeyStroke keyStroke = KeyStroke.getKeyStroke("pressed A");    // A simple reference - Works
        //KeyStroke keyStroke = KeyStroke.getKeyStroke("typed ?");      // Works
        KeyStroke keyStroke = KeyStroke.getKeyStroke("meta typed ?");   // What we want - Does not work

        // If we provide an invalid keystroke we get a null back - fail fast
        if (keyStroke==null) throw new RuntimeException("Invalid keystroke");

        // Create a simple menuItem linked to our action with the keystroke as accelerator
        JMenuItem helpMenuItem = new JMenuItem(new HelpAction());
        helpMenuItem.setAccelerator(keyStroke);

        // Install the menubar with a help menu
        JMenuBar mainMenu = new JMenuBar();
        JMenu helpMenu = new JMenu("Help");
        helpMenu.add(helpMenuItem);
        mainMenu.add(helpMenu);

        setJMenuBar(mainMenu);
    }

    // Scaffolding
    public static void main(String[] pArgs) {
        HelpShortcut helpShortcut= new HelpShortcut();
        helpShortcut.setLocationRelativeTo(null);
        helpShortcut.setSize(new Dimension(100, 162));
        helpShortcut.setVisible(true);
    }

    private class HelpAction extends AbstractAction {

        public HelpAction() {
            putValue(Action.NAME,"Help me!");

        }

        @Override
        public void actionPerformed(final ActionEvent pActionEvent) {
            JOptionPane.showMessageDialog(HelpShortcut.this,"You should ask StackOverflow!");
        }

    }
}
7
задан Løkling 16 November 2011 в 21:53
поделиться