Overriding the Default Action of a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Overriding the Default Action of a JTextComponent

Demo Code

import java.awt.event.ActionEvent;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JTextArea;
import javax.swing.text.JTextComponent;
import javax.swing.text.Keymap;

public class Main {
  public static void main(String[] argv) {
    JTextArea component = new JTextArea();
    Action defAction = findDefaultAction(component);

    component.getKeymap().setDefaultAction(new MyDefaultAction(defAction));
  }/* www. jav a 2  s  .  c o  m*/

  public static Action findDefaultAction(JTextComponent c) {

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

class MyDefaultAction extends AbstractAction {
  Action defAction;

  public MyDefaultAction(Action a) {
    super("My Default Action");
    defAction = a;
  }

  public void actionPerformed(ActionEvent e) {
    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);
    }
  }
}

Related Tutorials