如何在运行时更改 JFormattedTextField 的格式? [英] How to change the format of a JFormattedTextField at runtime?
问题描述
我知道您可以将格式传递给 JFormattedTextField 构造函数,但是您将如何在运行时更改格式化程序?例如,我有一个字段应该被格式化为整数值,但是当某个组合框的值发生变化时,现在该字段应该采用浮点值.
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.
推荐答案
您可以调用 setFormatterFactory(JFormattedTextField.AbstractFormatterFactory) 在您的对象上.
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.
注意,DefaultFormatterFactory
的构造函数可以带多个格式化程序;默认的,没有焦点时的显示格式,有焦点时的编辑格式,以及字段有空值时的空格式.
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.
这篇关于如何在运行时更改 JFormattedTextField 的格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!