你为什么混合KeyBinding
和KeyListener
?
不要将KeyListener
/KeyAdapter
与 Swing 一起使用。始终使用KeyBindings
你应该做这样的事情来听SHIFT+ ENTER (它可以在按键释放或按键按下):
jta.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), "Shift+Enter released");
jta.getActionMap().put("Shift+Enter released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Shift+Enter released");
}
});
重要的部分是:
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true)
注意最后两个参数。true
用于在释放Keybinding
键时添加,但您可以在按下键时使用,并且会出现相同的结果。另一个参数用于何时关闭。false
SHIFT
另外要删除ENTER,您应该在按下的键上进行:
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
InputMap inputMap = jta.getInputMap();
inputMap.put(enter, "none");
请注意,我使用这意味着在按下false
键时放置键绑定。
这是一个例子:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JTextArea jta = new JTextArea(20, 20);
//remove enter pressed
KeyStroke enter = KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0, false);
InputMap inputMap = jta.getInputMap();
inputMap.put(enter, "none");
//add shift+enter keybinding can be on pressed or released i.e false or true
jta.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_DOWN_MASK, true), "Shift+Enter released");
jta.getActionMap().put("Shift+Enter released", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent ae) {
System.out.println("Shift+Enter released");
}
});
frame.add(jta);
frame.pack();
frame.setVisible(true);
}
});
}