Install your own action to text component : Key Stroke « Swing JFC « Java

Install your own action to text component


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);




Related examples in the same category

1.Responding to KeystrokesResponding to Keystrokes
2.set Accelerator with KeyStroke
3.Add KeyStroke to JTextArea
4.InputMap and KeyStrokeInputMap and KeyStroke
5.Overriding Many Default Typed Key Bindings in a JTextComponent