InsertAction.java Source code

Java tutorial

Introduction

Here is the source code for InsertAction.java

Source

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();
        component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(new Character(' '), 0), "none");

        component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("pressed SPACE"),
                insertSpaceAction.getValue(Action.NAME));

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

        JFrame f = new JFrame();
        f.add(component);
        f.setSize(300, 300);
        f.setVisible(true);
    }
}