OverrideDefAction

JTextArea component = new JTextArea();
Action defAction = findDefaultAction(component);

// Install the overriding default action
component.getKeymap().setDefaultAction(new MyDefaultAction(defAction));

public class MyDefaultAction extends AbstractAction {
    Action defAction;
    public MyDefaultAction(Action a) {
        super("My Default Action");
        defAction = a;
    }
    public void actionPerformed(ActionEvent e) {
        // Perform customizations here
        // This example upper cases all typed characters
        if (e.getActionCommand() != null) {
            String command = e.getActionCommand();
            if (command != null) {
                command = command.toUpperCase();
            }
            e = new ActionEvent(e.getSource(), e.getID(), command, e.getModifiers());
        }

        // Now call the installed default action
        if (defAction != null) {
            defAction.actionPerformed(e);
        }
    }
}

public Action findDefaultAction(JTextComponent c) {
    // Look for default action
    // Check local keymap
    Keymap kmap = c.getKeymap();
    if (kmap.getDefaultAction() != null) {
        return kmap.getDefaultAction();
    }

    // Check parent keymaps
    kmap = kmap.getResolveParent();
    while (kmap != null) {
        if (kmap.getDefaultAction() != null) {
            return kmap.getDefaultAction();
        }
        kmap = kmap.getResolveParent();
    }
    return null;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.