[英]How to set the value of a JFormatedTextField to an invalid String before it gets changed by the user?
because of a project I want to how to set the value of a JFormatedTextField, in a Java Swing GUI, to an invalid String, before the user changes the value oby himself.因为一个项目,我想知道如何在用户自己更改值之前,在 Java Swing GUI 中将 JFormatedTextField 的值设置为无效的字符串。
Considering the fact that all the iddentifer names in the original code, which contains additional code, which is not usefull for this question, I decided to write a new short code, which contains the important part, for my question.考虑到原始代码中的所有标识符名称都包含额外的代码,这对这个问题没有用,我决定为我的问题编写一个新的短代码,其中包含重要的部分。
This is a shortened version of my code:这是我的代码的简化版本:
import javax.swing.*;
import javax.swing.text.*;
import java.text.*;
import java.awt.*;
public class myGUI{
private JFrame f;
private JPanel p;
private JFormattedTextField ftf;
private NumberFormat nf;
private NumberFormatter nfter;
public myGUI(){
f = new JFrame("My Window");
f.setSize(960,450);
f.setDefaultCloseOperation(f.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
f.setVisible(true);
p = new JPanel();
f.add(p);
p.setLayout(new FlowLayout());
nf = NumberFormat.getInstance();
nfter = new NumberFormatter(nf);
nfter.setAllowsInvalid(false);
ftf = new JFormattedTextField(nfter);
p.add(ftf);
ftf.setValue("I want this as my ftfs value before it gets changed");
}
}
When I execute this code, I get this error message:当我执行此代码时,我收到此错误消息:
java.lang.IllegalArgumentException: Cannot format given Object as a Number (in java.text.DecimalFormat)
java.lang.IllegalArgumentException:无法将 Object 格式化为数字(在 java.text.DecimalFormat 中)
I tried to solve this problem by myself by changing "nfter.setAllowsInvalid(false);"我试图通过更改“nfter.setAllowsInvalid(false);”自己解决这个问题。 to "nfter.setAllowsInvalid(true);"
到“nfter.setAllowsInvalid(true);” but I received the same result.
但我收到了相同的结果。
Since I am not really familiar to Swing and only familiar to the most basic things about Java, I hope you can help me, with your experance and knowledge.由于我对Swing不是很熟悉,只熟悉Java的最基本的东西,希望你能用你的经验和知识帮助我。
thanks for helping and sorry for my bad english skills!感谢您的帮助,抱歉我的英语水平不好!
Please use setText
instead of setValue
.请使用
setText
而不是setValue
。 You should put a number inside setValue
method like setValue(99)
.您应该在
setValue
方法中放入一个数字,例如setValue(99)
。
ftf.setText("I want this as my ftfs value before it gets changed");
And don't forget nfr.setCommitsOnValidEdit(true)
if you want your default text to be formatted as a number at beginning.如果您希望在开始时将默认文本格式化为数字,请不要忘记
nfr.setCommitsOnValidEdit(true)
。 Otherwise you will get null
value before you typing something.否则,您将在输入内容之前获得
null
值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.