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

最佳答案

您可以在对象上调用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的构造函数可以采用多个格式化程序。一种默认值,一种是没有焦点时的显示格式,一种是没有焦点时的编辑格式,以及字段具有空值时的null格式。

10-05 21:12
查看更多