Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the format of a JFormattedTextField at runtime?

Tags:

java

swing

I know you can pass a format to JFormattedTextField constructor, but how would you change the formatter at runtime? For example I have a field that is supposed to be formated to integer values, but when a value of a certain combo box is changed, now the field is supposed to take float values.

like image 682
m0s Avatar asked Mar 05 '11 15:03

m0s


2 Answers

You could invoke setFormatterFactory(JFormattedTextField.AbstractFormatterFactory) on your object.

You can use it in this fashion:

// Define the number factory.
NumberFormat nf = NumberFormat.getIntegerInstance(); // Specify specific format here.
NumberFormatter nff = new NumberFormatter(nf);
DefaultFormatterFactory factory = new DefaultFormatterFactory(nff);

// Define the decimal factory.
DecimalFormat df = new DecimalFormat(); // And here..
NumberFormatter dnff = new NumberFormatter(df);
DefaultFormatterFactory factory2 = new DefaultFormatterFactory(dnff); 

// Then you set which factory to use.
JFormattedTextField field = new JFormattedTextField();
field.setFormatterFactory(factory);
//field.setFormatterFactory(factory2);        

So just set the factory when your event occurs.

Note that the constructor of DefaultFormatterFactory can take several formatters; a default one, a display format when it doesn't have focus, an edit format when it has focus, and a null format for when the field has a null value.

like image 131
Morten Kristensen Avatar answered Sep 30 '22 08:09

Morten Kristensen


This example uses InputVerifier to add variations to a default format. It's designed for Date, but you might be able to adapt the approach to Number.

like image 36
trashgod Avatar answered Sep 30 '22 09:09

trashgod