Java JFormattedTextField中未清除的值
我发现很难清除Java JFormattedTextField中未清除的值,java,swing,jformattedtextfield,Java,Swing,Jformattedtextfield,我发现很难清除JFormattedTextFields的值。怎么做 我试过了 txtJFormattedTextField.setText(""); 但当焦点再次丢失时,我清除的值将出现。我阅读了关于这个问题的API 下面是我为日期字段创建JTFormattedTextFields的工厂- public static JFormattedTextField createDateField() { MaskFormatter maskFormatter = null;
JFormattedTextField
s的值。怎么做
我试过了
txtJFormattedTextField.setText("");
但当焦点再次丢失时,我清除的值将出现。我阅读了关于这个问题的API
下面是我为日期字段创建JTFormattedTextFields的工厂-
public static JFormattedTextField createDateField() {
MaskFormatter maskFormatter = null;
try {
maskFormatter = new MaskFormatter("##/##/####");
} catch (ParseException e) {
e.printStackTrace();
}
JFormattedTextField formattedTextField = new JFormattedTextField(
maskFormatter);
SwingHelper.installDateValidation((AbstractDocument) formattedTextField
.getDocument());
formattedTextField.setColumns(10);
return formattedTextField;
}
试过
try {
((JFormattedTextField) txtSigninDate).commitEdit();
} catch (ParseException e) {
e.printStackTrace();
}
结果是一个异常-下面是异常跟踪
java.text.ParseException: stringToValue passed invalid value
at javax.swing.text.MaskFormatter.stringToValue(MaskFormatter.java:456)
at javax.swing.text.MaskFormatter.stringToValue(MaskFormatter.java:371)
at javax.swing.JFormattedTextField.commitEdit(JFormattedTextField.java:530)
at app.view.action.Authentication_Action.clearSigninFields(Authentication_Action.java:207)
at app.view.action.authentication.AuthenticationCommand.decorateSignout(AuthenticationCommand.java:285)
at app.view.action.authentication.AuthenticationCommand.executeSignin(AuthenticationCommand.java:122)
at app.view.action.Authentication_Action$2.actionPerformed(Authentication_Action.java:292)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
尝试添加
formattedTextField.commitEdit();
设置文本后 1.取决于所用的
格式化程序
JFormattedTextField.setValue(0.00);
2.orMaskFormatter
JFormattedTextField.setValue(null);
3.可以使用Formatter
为JFormattedTextField
设置null
值,但我建议为具体的Formatter
使用适当的值,例如NumberFormatter
设置setValue(0.00)
4.为了获得更好的帮助,请尽快发布,否则您的问题可能无法回答,您看到这种行为的原因是JFormattedTextField
在focusLost
和commit
上还原为最后一个有效值。通常,您的代码应该使用值的getter和setter与这样的字段交互,而不是像常规JTextComponent
那样使用文本的getter和setter
因此,解决方案是设置一个值,该值由格式化程序格式化为空字符串
有关更多信息,请参阅。使用格式化程序工厂时,JFormattedTextField将返回输入的旧值的原因是,当字段失去焦点时,它会验证输入或缺少输入
答案很简单,可以在java文档网站上找到
在你的情况下,这就是它的工作原理
txtJFormattedTextField.setFocusLostBehavior(JFormattedTextField.PERSIST);
在创建文本字段后添加这一行,当焦点丢失时,它将不再尝试验证输入,换句话说,即使字段的当前值为“无效”,也将保留该字段的当前值
我把工厂发了出去。很抱歉没有添加SSCCE。但是我发现JFormattedTextField.setValue(null)代码>起作用。这里是堆栈溢出。你会添加到你提到的java文档的链接吗?海报ir指的是焦点行为,而不是以编程方式设置值。