Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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) throws Exception {
        JTextField component = new JTextField(10);

        // Override letter a
        component.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke("typed a"), "actionName");

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

        MyAction action = new MyAction();

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

        component.getActionMap().put(action.getValue(Action.NAME), action);
    }
}

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

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

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