简体   繁体   中英

How to change the format of a JFormattedTextField at runtime?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM