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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With