Overriding a Few Default Typed Key Bindings in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Overriding a Few Default Typed Key Bindings in a JTextComponent

Demo Code

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.JTextField;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) {
    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");

    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("typed X"), "none");

    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("shift pressed SPACE"), "actionName");

    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke(new Character(' '), 0), "none");

    //from w w w  .ja v a  2s .c  o m
     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) {
        }
      }
    };
    
    component.getInputMap(JComponent.WHEN_FOCUSED).put(
        KeyStroke.getKeyStroke("pressed SPACE"),
        insertSpaceAction.getValue(Action.NAME));

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


  }
}

Related Tutorials