Overriding Many Default Typed Key Bindings in a JTextComponent - Java Swing

Java examples for Swing:JTextComponent

Description

Overriding Many Default Typed Key Bindings in a JTextComponent

Demo Code


import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;

public class Main {
  public static void main(String[] argv) {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());
  }//w  w  w  .ja va  2 s.  c om

}

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 Tutorials