|
Feb
07
|
To restrict the number of characters that the user can enter into a text field can be achieved by either using a JFormattedTextField or using a custom Document with any JTextComponent.
To implement this using a JFormattedTextFiled is simply a matter of specifying the appropriate MaskFormatter to meet your requiremenets.
JTextField field = new JFormattedTextField(new MaskFormatter("***"));
The following class gives an example of how a custom Document can be implemented for use in any text component.
public class FixedSizeDocument extends PlainDocument
{
private int max = 10;
public FixedSizeDocument(int max)
{
this.max = max;
}
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException
{
// check string being inserted does not exceed max length
if (getLength()+str.length()>max)
{
// If it does, then truncate it
str = str.substring(0, max - getLength());
}
super.insertString(offs, str, a);
}
}
You can then use this class with your JTextField for example using the following
field.setDocument(new FixedSizeDocument(5));



September 18th, 2009 at 12:19 am
Hi. This was just great. Much better and easier than suggestion at Sun and other Java sites.
September 18th, 2009 at 1:36 pm
Glad you liked it, thanks for the feedback
October 15th, 2009 at 5:50 am
Mr Swing is right. I tried this solution and it worked great!!! This is the best solution that I found on the web and I’ve been searching for days already and I always ended up being linked to those complicated solutions on different websites. Thanks a lot!!! I really really appreciate it
June 3rd, 2010 at 1:47 am
Best solution on the web. Far simpler than the many other “solutions” I found. Thanks.
June 3rd, 2010 at 8:30 am
Thanks, glad you found it useful.
June 22nd, 2010 at 12:15 pm
Wow. This solution really worked and very simple to understand for java beginners like me. Thank a lot!
June 22nd, 2010 at 12:18 pm
Thanks Eric.
October 22nd, 2010 at 12:54 am
Great job
December 9th, 2010 at 9:32 pm
really easy, I like it
October 5th, 2011 at 8:28 pm
Set up a keytyped event on the textfield
if (jTextField1.getText().length()>=2){
evt.consume();
}
October 5th, 2011 at 8:33 pm
Using a KeyListener will be problematic for cut and paste, and if the text field change is not caused by typing (eg. if its value is programatically changed)
October 7th, 2011 at 3:31 pm
Thanks….
This solution helped me and it works fine.
December 14th, 2011 at 6:22 pm
thanks for the post, helped me..