如何在运行时更改JFormattedTextField的格式?

时间:2011-03-05 15:24:55

标签: java swing

我知道您可以将格式传递给JFormattedTextField构造函数,但是如何在运行时更改格式化程序?例如,我有一个应该被格式化为整数值的字段,但是当某个组合框的值被更改时,现在该字段应该采用浮点值。

2 个答案:

答案 0 :(得分:8)

您可以在对象上调用setFormatterFactory(JFormattedTextField.AbstractFormatterFactory)

您可以这种方式使用它:

// 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);        

因此,只需在事件发生时设置工厂。

请注意DefaultFormatterFactory的构造函数可以使用多个格式化程序;默认值,没有焦点时的显示格式,焦点时的编辑格式,以及字段空值时的空格式。

答案 1 :(得分:1)

example使用InputVerifier将变体添加到默认格式。它专为Date设计,但您可以将方法调整为Number