tags:

views:

425

answers:

4

Anybody know if there is an easy way to limit the allowed characters for a JTextArea. I.e. similar to JTextField using MaskFormatter.

Specifically I want to limit the allowed characters for a JTextArea to only uppercase characters and only a very limited set characters like !"#¤%&/()=

A: 

Try to extend PlainDocument and change the method insertString() to filter out all unwanted characters and replace lower with uppercase letters. Then you can use this special document in your JTextArea.

Aaron Digulla
The new approach is to use a DocumentFilter so the code is reusable on a JTextField, JTextArea, or JTextPane. The only limitation is that the Document used extend from AbstractDocument.
camickr
+2  A: 

Implement a javax.swing.text.DocumentFilter to remove inappropriate characters. Set that on your favourite AbstractDocument and construct you JTextArea with that.

Tom Hawtin - tackline
A: 

You can assign a filter to JTextArea document. Just override the method insertString in the class DocumentFilter to ignore the characters

jassuncao
Erm, and replace.
Tom Hawtin - tackline
+2  A: 

You may find the concept of Chaining Document Filters interesting. The first filter would automatically convert lower case characters to upper case (included in above link) so the user doesn't have to worry about this, then the second filter would validate all the characters (you would need to write your own).

camickr