简体   繁体   中英

Replace Keybinding In Text Field With Existing Action

I have a JTextPane . I want my own behavior for Ctrl+Arrow presses.

jTextEntryPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()), Controls.UP_ACTION);
jTextEntryPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()), Controls.DOWN_ACTION);
jTextEntryPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()), Controls.LEFT_ACTION);
jTextEntryPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, Toolkit.getDefaultToolkit ().getMenuShortcutKeyMaskEx()), Controls.RIGHT_ACTION);
jTextEntryPane.getActionMap().put(Controls.UP_ACTION, new MoveAction(Controls.UP_ACTION, this));
jTextEntryPane.getActionMap().put(Controls.DOWN_ACTION, new MoveAction(Controls.DOWN_ACTION, this));
jTextEntryPane.getActionMap().put(Controls.LEFT_ACTION, new MoveAction(Controls.LEFT_ACTION, this));
jTextEntryPane.getActionMap().put(Controls.RIGHT_ACTION, new MoveAction(Controls.RIGHT_ACTION, this));

Ctrl+Up and Ctrl+Down work.

Ctrl+Left and Ctrl+Right do not, but instead are being used by the text field (to go to the beginning or end of the input field). I want to replace their behavior, but I do not want to change the regular arrow (left and right) behavior. How do I do this?

Ctrl+Up and Ctrl+Down are currently not defined as key bindings for the text field so you are just adding new bindings, which is why they work.

However, Ctrl+Left and Ctrl+Right are already defined as bindings for a JTextField. They are defined for the WHEN_FOCUSED InputMap which has priority over the WHEN_IN_FOCUSED_WINDOW InputMap.

jTextEntryPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)....

You are using the wrong InputMap for all your bindings.

You should be using:

jTextEntryPane.getInputMap()....

which will use the WHEN_FOCUSED InputMap.

This will allow you to replace the default Action.

See Key Bindings for a simple program that displays all the default bindings for each component.

Edit:

Tabbing is not handled by the Key Bindings. It is handled by the focus subsystem, so the event is intercepted before it gets to the text field. I believe the following should work:

textField.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS, null);
textField.setFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM