JFormattedTextField 和 getValue 与 getText

JFormattedTextField and getValue vs. getText

阅读文档后,我不清楚 getValuegetText 对于 JFormattedTextField 的区别。

在我的代码中,getText 给出了我认为我需要的东西,而 getValue 总是 return 为空。

在我看来,根据文档,它们应该 return 至少在字段之后,当格式正确时,它们会失去焦点。

getValue 方法应该 "Returns the last valid value."

一个简单的解释会有所帮助。

好吧 JFormattedTextField 是一个文本组件,允许保留 并为其提供自定义字符串表示(格式)。

此值是一个对象,通常是日期或数字实例,这两个 类 具有最不同的格式。

话虽如此,getValue() returns the value held by formatted text field component while getText() returns 值的字符串表示形式。

有关此组件的更多详细信息,请查看 How to Use Formatted Text Fields:

A formatted text field's text and its value are two different properties, and the value often lags behind the text.

The text property is defined by the JTextField class. This property always reflects what the field displays. The value property, defined by the JFormattedTextField class, might not reflect the latest text displayed in the field. While the user is typing, the text property changes, but the value property does not change until the changes are committed.

To be more precise, the value of a formatted text field can be set by using either the setValue method or the commitEdit method. The setValue method sets the value to the specified argument. The argument can technically be any Object, but the formatter needs to be able to convert it into a string. Otherwise, the text field does not display any substantive information.

假设你有

JFormattedTextField text = new JFormattedTextField(new DecimalFormat("####.##"));

这是一个简单的数字 JFormatedTextField。您输入 12(有效输入),两个值将相同。如果输入"Hello",这是无效的,getValue()不会返回。

您可能在文本字段中输入了无效数据。