How to restrict Charachters in JTextbox

Hello everyone,
     I cannot seem to find a way how to restrict the number of charachters in a JTextbox. I know that there is this Constructor where you can pass the COLUMN size but that doesnt work. Java 1.4 has this JFormattedTextbox where you can set the mask and specify something like "####" to restrict the entries to only 4 charachters, but that has a problem. By default it puts blanks in the textfield and that is a problem.
Thanks
- Adil
AdilKAsked:
Who is Participating?
 
TimYatesCommented:
That link shows you the Pre JDK1.4 way, and the after JDK1.4 way :-)

Good luck!!  

Tim
0
 
CEHJCommented:
Can't test this at the moment but try


JTextField tf = new JTextField(4);
tf.setDocument(new FourCharDoc());

.....

class FourCharDoc extends PlainDocument {
      public void insertString(int offs,String str,AttributeSet a) throws BadLocationException {
            if (getLength() < 4)
                  super.insertString(offs,str,a);
      }
      
}
0
 
CEHJCommented:
Didn't see that link before post sorry. Use the code they give, not mine.
0
 
TimYatesCommented:
:-)
0
All Courses

From novice to tech pro — start learning today.