La combinaison de touches standard pour l'aide est command - ? sur les macs. Comment puis-je lier cette combinaison de touches à un élément de menu.
Note : Comme nos utilisateurs ont des claviers différents, je cherche une solution qui ne nécessite pas de savoir sur quelle touche se trouve " ?".
Utilisation de KeyStroke.getKeyStroke(String)
ce que dit la 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_".
J'ai cet exemple de 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!");
}
}
}