Troubleshooting

Restricting text characters

How can I restrict the characters that a user enters in a text field or a text area?

Restricting what characters a user can input is accomplished in a manner that is very similar to restricting the total number of characters that are input—as shown in the TextListenerDemo application. To see how this is accomplished, the following textValueChanged method prevents a user from entering lowercase letters:

 public void textValueChanged (TextEvent e) { TextField tf = (TextField) e.getSource (); StringBuffer text = new StringBuffer (tf.getText ()); int cp = tf.getCaretPosition (); if (cp == 0) return; char ch = text.charAt (cp - 1); if (Character.isLowerCase (ch)) { ch = Character.toUpperCase (ch); ...

Get Special Edition Using Java 2 Standard Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.