Overriding Many Default Typed Key Bindings in a JTextComponent : Key Stroke « Swing JFC « Java

Overriding Many Default Typed Key Bindings in a JTextComponent


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

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

class MyKeyListener extends KeyAdapter {
  public void keyTyped(KeyEvent evt) {
    JTextComponent c = (JTextComponent) evt.getSource();
    char ch = evt.getKeyChar();

    if (Character.isLowerCase(ch) == false) {
    try {
      c.getDocument().insertString(c.getCaretPosition(), "" + Character.toUpperCase(ch), null);
    } catch (BadLocationException e) {

public class Main {
  public static void main(String[] argv) throws Exception {
    JTextField component = new JTextField();
    component.addKeyListener(new MyKeyListener());

    JFrame f = new JFrame();
    f.setSize(300, 300);


Related examples in the same category

1.Responding to KeystrokesResponding to Keystrokes
2.set Accelerator with KeyStroke
3.Add KeyStroke to JTextArea
4.InputMap and KeyStrokeInputMap and KeyStroke
5.Install your own action to text component