The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.text  [49 examples] > Actions and Key Bindings  [5 examples]

e1001. Overriding the Default Action of a JTextComponent

The default action in a text component keymap receives all typed characters that are not handled in any inputmap or keymap. This example demonstrates how to wrap the default action of a text component with a custom default action.
    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;
    }

 Related Examples
e1002. Creating a Custom Editing Command for a JTextComponent
e1003. Overriding a Few Default Typed Key Bindings in a JTextComponent
e1004. Overriding Many Default Typed Key Bindings in a JTextComponent
e1005. Listing the Key Bindings in a JTextComponent Keymap

See also: Caret and Selection    Events    JEditorPane    JFormattedTextField    JTextArea    JTextComponent    JTextField    JTextPane    Styles   


© 2002 Addison-Wesley.