JFormattedTextField..is it really this hard to use?

Hi,

I'm using JFormattedTextField to read in user input. The input needs to be a valid 5 digits number so i used DecimalFormat and NumberFormatter to put restrictions on the input, and i set the setAllowsInvalid() to false. The problem i'm having now is that when i type in some number and then i want to delete it using backspace the JFormattedTextField doesn't allow me to delete the first digit, also when i try to clear the text field using setText("") it doesn't function. I'll appreciate any help you guys can offer. For the moment i'm even thinking of getting rid of JFormattedTextField alltogether and using JTextField with custom Document and InputVerifier. Thanks in advance

[704 byte] By [zehda_a] at [2007-9-30 0:39:30]
# 1

Hi,

JFormattedTextField works with values, if you have set a Format to the JFormatted TextField it will be using a class for its value (Double, Integer)

If you want to add the format to the JFormattedTextField:

NumberFormat = NumberFormat.getIntegerInstance();

or

NumberFormat = NumberFormat.getNumberInstance();

and use the appropiate format procedures, the output of the JFormattedTextField will depend on the format its using to print and receive the data.

For setting a Value, rather than using setText(""); use setValue(Number Class);

so you could do:

vfield.setValue(new Double(0));

probably (not sure of this) you could do vfield.setValue(null);

Also for getting the value you could use vfield.getValue() that returns an Object that you can cast to Double or Integer depending of what you need....

Hope that helps...

Alex

alejandrosha at 2007-7-16 5:11:03 > top of Java-index,Archived Forums,Swing...
# 2

The problem is that once you've got a value in the JFormattedTextField, it won't allow an invalid value.

Since deleting all the characters would result in an invalid number (e.g.new Integer("") throws an

exception), you cannot delete the last digit.

As far as clearing the field, you need to use setValue( null ) rather than settText("").

If you just need a five digit number, you could use a MaskFormatter with the mask set to "#####".

This will only accept a five digit number. If just three digits are entered and the user tabs off, the

entry is not accepted and the value remains null.

However, this has a similar problem: once a valid value is accepted, you cannot delete it. The

easiest way around that is to create a simple subclass of JFormattedTextField which overrides

processFocusEvent as in this thread http://forum.java.sun.com/thread.jsp?forum=57&thread=475909

(third to the last post).

: jay

JayDSa at 2007-7-16 5:11:03 > top of Java-index,Archived Forums,Swing...