How to disable default textfield shortcuts in JTextField

余生长醉 提交于 2019-12-08 08:23:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!