问题
I have a custom textfield class that extends the JTextField class in Swing.
I need to find a way to disable the default actions for Ctrl-A (select all), Ctrl-H (backspace) etc, so that the window containing the textfield can map these shortcuts to whatever it wants.
Any help would be greatly appreciated.
回答1:
Okay, found the answer myself:
Added the following to an initilization method of the textfield class:
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_MASK), "none");
The effect is that the textfield ignores the shortcut and lets the keystroke be passed along to the shortcut handler in the window.
回答2:
How to make and remove key bindings would help you to implement.
To remove all of default key bindings, just dereference its parent InputMap.
jtextField.getInputMap().setParent(null);
But it remove all of key bindings so that you can't type any characters. JTextField's input has 3 parents. So you would be better with overriding specific key bindings as below.
InputMap inputMap = jtextfield.getInputMap();
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Key_Event.CTRL_DOWN_MASK), "foo");
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_A, Key_Event.META_DOWN_MASK), "foo");
回答3:
Maybe you should deal with the KeyMap.
来源:https://stackoverflow.com/questions/1476462/how-to-disable-default-textfield-shortcuts-in-jtextfield