Frage

Is it possible to set MaskFormatter of a JFormatterTextField to ##,## and the value type of the JFormatterTextField to Float? I tried it using the following mask for a default formatter factory but it does not work and the getValue().getClass() gives me java.lang.String.

DefaultFormatterFactory dff = new DefaultFormatterFactory();
mf = new MaskFormatter("##,##);
mf.setValueClass(Float.TYPE);
dff.setDefaultFormatter(mf);
field.setFormatterFactory(dff);

And the problem with number formatting is that it doesn't mask the field for me.

PS. My default system configuration uses "," as "." in the English one. So it's not the problem and I brought it just for precision.

War es hilfreich?

Lösung

You are running into a bit of a limitation of JFormattedTextField here.

If you use DecimalFormat http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html you can set up the display to look however you like but it does not rigidly enforce what the user types. The returned result will be a number.

If you use MaskFormatter then you get the rigid enforcement, but the value returned is a string.

You could use the MaskFormatter and simply pass it to Float.valueOf(str) when you need the result. The alternative is to either implement your own format object or to listen on some of the events provided by the text field and/or its backing document and directly do your own control of the users entry.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top