Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to bind command-? as a swing action accelerator for a help menu?
    text
    copied!<p>The standard key combination for help is <kbd>command</kbd>-<kbd>?</kbd> on macs. How can I bind this key combination to a menu item. </p> <p>Note: As our users have different keyboard layouts I´m looking for a solution that does not require knowledge about what key "?" is located on.</p> <p>Using <code>KeyStroke.getKeyStroke(String)</code>, which javadoc says; </p> <pre><code>Parses a string and returns a `KeyStroke`. The string must have the following syntax: &lt;modifiers&gt;* (&lt;typedID&gt; | &lt;pressedReleasedID&gt;) modifiers := shift | control | ctrl | meta | alt | button1 | button2 | button3 typedID := typed &lt;typedKey&gt; typedKey := string of length 1 giving Unicode character. pressedReleasedID := (pressed | released) key key := KeyEvent key code name, i.e. the name following "VK_". </code></pre> <p>I have this example code: </p> <pre><code>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!"); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload