Install your own action to text component : InputMap « Swing Event « Java Tutorial

import java.awt.event.ActionEvent;

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

class InsertAction extends AbstractAction {
  public InsertAction() {
    super("Insert Space");

  public void actionPerformed(ActionEvent evt) {
    JTextComponent c = (JTextComponent) evt.getSource();

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

public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField(10);
    InsertAction insertSpaceAction = new InsertAction();
        KeyStroke.getKeyStroke(new Character(' '), 0), "none");

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

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

    JFrame f = new JFrame();
    f.setSize(300, 300);

15.4.1.void InputMap.put(KeyStroke keyStroke, Object actionMapKey)
15.4.2.InputMap javax.swing.JComponent.getInputMap(int condition)
15.4.3.Press shift space or shift F2 to move the focus to the previous focusable component.
15.4.4.Modify a component: press space bar or F2 to move focus to next focusable component.
15.4.5.Adding an InputMap to a Component
15.4.6.Sharing an InputMap or an ActionMap Between Two Components
15.4.7.Overriding Default Typed Key Bindings in a JTextComponent
15.4.8.Disable a character so that no action is invoked
15.4.9.Prevent the space from being inserted when shift-space is pressed
15.4.10.Install your own action to text component