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]

e1004. Overriding Many Default Typed Key Bindings in a JTextComponent

See e1003 Overriding a Few Default Typed Key Bindings in a JTextComponent for information about default typed key bindings in a text component.

There are two ways to override the default key bindings in a text component. This example demonstrates a technique when many characters need to be overridden. This example converts all lowercase characters to uppercase. See e1004 Overriding Many Default Typed Key Bindings in a JTextComponent for a technique suitable for overriding a few characters.

    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
    
    public class MyKeyListener extends KeyAdapter {
        public void keyTyped(KeyEvent evt) {
            JTextComponent c = (JTextComponent)evt.getSource();
            char ch = evt.getKeyChar();
    
            if (Character.isLowerCase(ch)) {
                try {
                    c.getDocument().insertString(
                        c.getCaretPosition(), ""+Character.toUpperCase(ch), null);
                    evt.consume();
                } catch (BadLocationException e) {
                }
            }
        }
    }

 Related Examples
e1001. Overriding the Default Action of a JTextComponent
e1002. Creating a Custom Editing Command for a JTextComponent
e1003. Overriding a Few 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.