views:

369

answers:

3

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.

A: 

Hi,

Maybe you should deal with the KeyMap.

Regards.

ATorras
+1  A: 

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.

Rolf
+1  A: 

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");
xrath