I want to limit the input in a textfield to a certain size. The value in
that field will be used as a String. When that size is reached, any new
characters the user types will not be added to the textfield.
I've tried to solve this using a JFormattedTextField. I discovered only one
way to accomplish something like described above by using a MaskFormatter
and feed it with E.g. a formatstring like "**********" to limit the input to
10 characters. But then, the JFormattedTextField appends spaces to the end
of the text when it does not reach the size limit, and I don't want that.
Can this be circumvented in any way, using JFormattedTextField? And if so,
how? Or should I use a custom Document-model to accomplish what I want?
Thanks for any advice given.
Best regards,
Dave
ak - 16 Jan 2004 21:58 GMT
> I've tried to solve this using a JFormattedTextField. I discovered only one
> way to accomplish something like described above by using a MaskFormatter
[quoted text clipped - 4 lines]
> Can this be circumvented in any way, using JFormattedTextField? And if so,
> how? Or should I use a custom Document-model to accomplish what I want?
custom Document is surely the best way.
public class LimitedDocument extends PlainDocument {
int limit;
public void insertString(int offset, String str, AttributeSet a) throws
BadLocationException {
int maxLen limit - offset;
if(str.length() < maxLen) {
super.insertString(offset, str, a);
}
else {
super.insertString(offset, str.substring(0, maxLen, a);
}
}
}
--
____________
http://reader.imagero.com the best java image reader.
ak - 16 Jan 2004 22:00 GMT
> else {
> super.insertString(offset, str.substring(0, maxLen, a);
> }
grrr, I forgot one brace:
else {
super.insertString(offset, str.substring(0, maxLen), a);
}
--
____________
http://reader.imagero.com the best java image reader.
Lee Weiner - 16 Jan 2004 22:18 GMT
>I want to limit the input in a textfield to a certain size. The value in
>that field will be used as a String. When that size is reached, any new
[quoted text clipped - 8 lines]
>Can this be circumvented in any way, using JFormattedTextField? And if so,
>how? Or should I use a custom Document-model to accomplish what I want?
1. Create a subclass of PlainDocument.
2. Overwrite the insertString() method to check the length of the current
contents of the document plus the length of the string to be inserted. If
that is greater than the desired maximum length, do nothing, otherwise, call
super.insertString() to insert the text.
3. Add an instance of your subclass to a JTextField with setDocument().
Lee Weiner
lee AT leeweiner DOT org