幫助的標準組合鍵是命令 - ?在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!");
}
}
}
世界其他地方使用F1的幫助+1 – mKorbel
這是真的,但命令 - ?是特定於應用程序的幫助的os x標準以及用戶期望的內容 - ref http://support.apple.com/kb/ht1343 另一個有趣的問題是,在較新的Mac上,缺省值是將F-鍵映射到特殊功能(聲音,亮度等),而不是「F1」等,這樣,如果用戶沒有在鍵盤偏好設置中啓用它們,這個快捷鍵將不會執行任何操作。 –