How do I make text typed in a TextArea appear in uppercase only?

Tim Rohaly

The key to solving this problem is to subclass TextArea and intercept any KeyEvent sent. You need to check to see if the typed key is a lower case character (be careful to keep this independent of Locale!) - if it is, change it to upper case.

Here's a piece of code that will do this for you:

import java.awt.AWTEvent;
import java.awt.TextArea;
import java.awt.event.KeyEvent;

public class UpperCaseTextArea extends TextArea {

    public UpperCaseTextArea() {
        enableEvents(AWTEvent.KEY_EVENT_MASK);
    }

    public void processKeyEvent(KeyEvent e) {
        if ((e.getID() == KeyEvent.KEY_TYPED) &&
            Character.isLowerCase(e.getKeyChar()) ) {
            e.setKeyChar(Character.toUpperCase(e.getKeyChar()));
        }
        else {
            super.processKeyEvent(e);
        }
    }
}

And here's a little application you can use to test it:

import java.awt.Frame;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class UCTextAreaTest {

    public static void main(String[] args) {
        Frame f = new Frame();
        f.add(new UpperCaseTextArea(), BorderLayout.CENTER);
        f.addWindowListener(
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            }
        );
        f.setSize(200, 150);
        f.setVisible(true);
    }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact