Link to home
Start Free TrialLog in
Avatar of AdilK
AdilK

asked on

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
ASKER CERTIFIED SOLUTION
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That link shows you the Pre JDK1.4 way, and the after JDK1.4 way :-)

Good luck!!  

Tim
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);
      }
      
}
Didn't see that link before post sorry. Use the code they give, not mine.