java 如何在运行时更改 JFormattedTextField 的格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5204705/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change the format of a JFormattedTextField at runtime?
提问by m0s
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.
我知道您可以将格式传递给 JFormattedTextField 构造函数,但是您将如何在运行时更改格式化程序?例如,我有一个字段应该被格式化为整数值,但是当某个组合框的值发生变化时,现在该字段应该采用浮点值。
回答by Morten Kristensen
You could invoke setFormatterFactory(JFormattedTextField.AbstractFormatterFactory)on your object.
您可以在您的对象上调用setFormatterFactory(JFormattedTextField.AbstractFormatterFactory)。
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.
请注意,的构造函数DefaultFormatterFactory
可以采用多个格式化程序;默认的,没有焦点时的显示格式,有焦点时的编辑格式,以及当字段具有空值时的空格式。