Formatting a JTextField to a certain length with numbers only.

Hello,

What I want to is limit the user to a certain amount of numbers. If the user tries to exceeds the max length, i want it to beep and if they push anything but a number, i want it to beep :O

I got this to work for limitting the length using documents, but how can i make it so that only numbers are inputted also.

Thanks!

[351 byte] By [Rayz0rsa] at [2007-10-2 10:07:09]
# 1
> What I want to is limit the user to a certain amount of numbersUse a JFormattedTextField
camickra at 2007-7-13 1:24:29 > top of Java-index,Desktop,Core GUI APIs...
# 2
by saying use a JformattedTextField, do u mean use an input verifier....? If so, is it possible to stay away from the input verifier, and use documents?Sorry, i'm new to swing :|Thanks
Rayz0rsa at 2007-7-13 1:24:29 > top of Java-index,Desktop,Core GUI APIs...
# 3

Helo Rayzor,

I don't think Camickr meant to say that. You could do something like:

NumberFormat nf = NumberFormat.getNumberInstance();

nf.setMaximumIntegerDigits(5);

nf.setMinimumIntegerDigits(1);

JFormatedTextField ftf = new JFormattedTextField(nf);

If, however, the beep is important, I think you must use a DocumentListener instead.

Regards

J鰎g

Joerg22a at 2007-7-13 1:24:29 > top of Java-index,Desktop,Core GUI APIs...
# 4
Hello again,I have already used a numberformatter before, but my experience with it is that if you do not put in a valid integer, and you click off the jformattedtextfield, the text just disappears.
Rayz0rsa at 2007-7-13 1:24:29 > top of Java-index,Desktop,Core GUI APIs...
# 5

> I got this to work for limitting the length using documents, but how can i make it so that only numbers are inputted also.

If you don't like the way the JFormattedTextField works, then you need to add code to your custom Document make sure each character entered is a valid character. Simply loop through the input String and validate each character individiually.

Also, the new approach for this kind of customization is to use a DocumentFilter, not override the Document. The Swing tutorial on [url http://java.sun.com/docs/books/tutorial/uiswing/components/generaltext.html#filter]Text Component Features[/url] has an example of this.

camickra at 2007-7-13 1:24:29 > top of Java-index,Desktop,Core GUI APIs...