帮助的标准组合键是 command-? 在 mac 上。如何将此组合键绑定(bind)到菜单项。
注意:由于我们的用户有不同的键盘布局,我正在寻找一种不需要了解什么键“?”的解决方案。位于。
使用 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!");
}
}
}
最佳答案
在我的键盘上“?”位于“/”键上方,因此您还可以在旁边使用 shift 键键入“?”。所以要进行绑定(bind),您需要使用:
// KeyStroke keyStroke = KeyStroke.getKeyStroke("meta typed ?");
int modifier = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()
+ KeyEvent.SHIFT_DOWN_MASK;
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, modifier);
关于java - 如何绑定(bind)命令-?作为帮助菜单的 Swing Action 加速器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8157245/