OverrideKey

JTextField component = new JTextField(10);

// Override a, A, 9, -, $
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed a"), "actionName");
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed A"), "actionName");
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed 9"), "actionName");
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed -"), "actionName");
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed $"), "actionName");

// Overriding space must be done this way
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke(new Character(' '), 0), "actionName");

// Disable a character so that no action is invoked.
// The action name "none" is conventionally used to mean no action.
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("typed X"), "none");

// If you want to bind a keystroke to shift-space (which generates
// a space character), you need to use a pressed-type keystroke.
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("shift pressed SPACE"), "actionName");

// However, the above is not sufficient. Although it binds the action to shift-space,
// it does not mask the generated space character. So, not only will the action
// be invoked, a space character will be inserted into the text component.
// You need to disable the typed space character.
// This will prevent the space from being inserted when shift-space is pressed.
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke(new Character(' '), 0), "none");

// But if you still want a non-modified spaced key to insert
// a space, you need to add a pressed-type keystroke for space.
component.getInputMap(JComponent.WHEN_FOCUSED).put(
    KeyStroke.getKeyStroke("pressed SPACE"), insertSpaceAction.getValue(Action.NAME));

// Add action
component.getActionMap().put(insertSpaceAction.getValue(Action.NAME), insertSpaceAction);

public Action insertSpaceAction = new AbstractAction("Insert Space") {
    public void actionPerformed(ActionEvent evt) {
        JTextComponent c = (JTextComponent)evt.getSource();

        try {
            c.getDocument().insertString(c.getCaretPosition(), " ", null);
        } catch (BadLocationException e) {
        }
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.