到目前为止,我已经使用 ESC 键关闭窗口,使用以下代码:
KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
screen.dispose();
}
};
screen.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
screen.getRootPane().getActionMap().put("ESCAPE", escapeAction);
但我想知道如何添加 CTRL+A 事件?我记得读过有关为按键按下/释放设置 boolean 值的方法,但我没有看到使用这段代码,所以我想知道如何实现 CTRL+A。
谢谢
最佳答案
重要的是 KeyStroke.getKeyStroke(...)
方法的第二个参数,因为您需要在那里使用 InputEvent.CTRL_DOWN_MASK
让KeyEvent.VK_A 是一个控件-A。
例如,
KeyStroke ctrlAKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_A,
InputEvent.CTRL_DOWN_MASK);
我不会担心使用使用 boolean 值的 3 参数方法,因为您对按键更感兴趣,而不是按键按下或按键释放。
关于您的评论:
Correction to my earlier comment. It works, if I make it let's say Ctrl+W. Ctrl+A just attempts to do its native "select all" function in a textfield in the frame. Any way to avoid that?
据我所知,如果具有焦点的组件(例如 JTextArea)直接响应 ctrl-A 按键,这将是一个问题。要解决此问题,您可以向该组件添加相同的绑定(bind),但一定要将其绑定(bind)到使用 JComponent.WHEN_FOCUSED;
条件的 InputMap。
关于java - 将组合键绑定(bind)到 JFrame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10822787/