tags:

views:

39

answers:

2

I try to limit the number of allowable characters to 5 by using

    try {
        jFormattedTextField2.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("*****")));
    } catch (java.text.ParseException ex) {
        ex.printStackTrace();
    }

However, when I only enter 1 character, there will always be 4 others space being padded. How can I avoid the padding, at the same time limiting number of characters?

+1  A: 

Instead of a JFormattedTextField, use a plain JTextField. Change the textfield's document to accept only a specific number of characters by setting a custom document.

jackrabbit
A `DocumentListener` that rejects them??
Tom Hawtin - tackline
@Tom: don't know what I was thinking there with the listener. I'll change my answer to just mention the custom document. That one is mentioned in the Java Text tutorial. I agree that DocumentFilter is the way to go here.
jackrabbit
+6  A: 

JFormattedTextField leads to evil UIs.

The class you want is javax.swing.text.DocumentFilter. This allows you modify mutations in a chain-of-command style.

Tom Hawtin - tackline