2020年10月30日 | Leave a comment 问题: macos 上 setMnemonic 快捷键无效 解决: bindShotKey(btnSearch, "搜索", KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK, this::btnSearchActionPerformed); 1 bindShotKey(btnSearch, "搜索", KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK, this::btnSearchActionPerformed); static void bindShotKey(JButton btn, String actionKey, int keyCode, int modifier, Consumer<ActionEvent> handler) { Action searchAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.printf(" searchAction e:" + e); handler.accept(e); } }; searchAction.putValue(Action.MNEMONIC_KEY, keyCode); btn.getActionMap().put(actionKey, searchAction); //OK btnSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), KEY_SEARCH); btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyCode, modifier), actionKey); } 12345678910111213 static void bindShotKey(JButton btn, String actionKey, int keyCode, int modifier, Consumer<ActionEvent> handler) { Action searchAction = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { System.out.printf(" searchAction e:" + e); handler.accept(e); } }; searchAction.putValue(Action.MNEMONIC_KEY, keyCode); btn.getActionMap().put(actionKey, searchAction); //OK btnSearch.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0), KEY_SEARCH); btn.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(keyCode, modifier), actionKey);} 参考: