应用程序范围的键盘快捷键 - Java Swing

Lou*_*met 30 java swing keystroke shortcut

我想为Java Swing应用程序创建一个应用程序范围的键盘快捷方式.循环所有组件并在每个组件上添加快捷方式,具有焦点相关的副作用,并且看起来像是一个强力解决方案.

谁有清洁解决方案?

Tom*_*ine 39

对于每个窗口,使用JComponent.registerKeyboardAction条件为WHEN_IN_FOCUSED_WINDOW.或者使用:

JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, command);
JComponent.getActionMap().put(command,action);
Run Code Online (Sandbox Code Playgroud)

registerKeyboardAction API文档中所述.

  • x1001会更好,这样他至少可以得到一个upvote. (3认同)

Kar*_*arl 19

安装自定义KeyEventDispatcher.KeyboardFocusManager类也是此功能的好地方.

的KeyEventDispatcher


dan*_*ann 14

对于想知道(像我一样)如何使用KeyEventDispatcher的人来说,这是我放在一起的一个例子.它使用HashMap存储所有全局操作,因为我不喜欢大型if (key == ..) then .. else if (key == ..) then .. else if (key ==..) ..构造.

/** map containing all global actions */
private HashMap<KeyStroke, Action> actionMap = new HashMap<KeyStroke, Action>();

/** call this somewhere in your GUI construction */
private void setup() {
  KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK);
  actionMap.put(key1, new AbstractAction("action1") {
    @Override
    public void actionPerformed(ActionEvent e) {
      System.out.println("Ctrl-A pressed: " + e);
    }
  });
  // add more actions..

  KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();
  kfm.addKeyEventDispatcher( new KeyEventDispatcher() {

    @Override
    public boolean dispatchKeyEvent(KeyEvent e) {
      KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);
      if ( actionMap.containsKey(keyStroke) ) {
        final Action a = actionMap.get(keyStroke);
        final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null );
        SwingUtilities.invokeLater( new Runnable() {
          @Override
          public void run() {
            a.actionPerformed(ae);
          }
        } ); 
        return true;
      }
      return false;
    }
  });
}
Run Code Online (Sandbox Code Playgroud)

可能没有必要使用SwingUtils.invokeLater(),但最好不要阻止全局事件循环.


dan*_*ann 6

当您有菜单时,可以向菜单项添加全局键盘快捷键:

    JMenuItem item = new JMenuItem(action);
    KeyStroke key = KeyStroke.getKeyStroke(
        KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK);
    item.setAccelerator(key);
    menu.add(item);
Run Code Online (Sandbox Code Playgroud)