简体   繁体   English

NumberFormat解析不够严格

[英]NumberFormat parse not strict enough

I have a JFormattedTextField with a NumberFormat with Locale.US. 我有一个带有Locale.US的NumberFormatJFormattedTextField So the decimal separator is the point and the grouping separator is the comma. 因此,小数点分隔符是点,分组分隔符是逗号。

Now I type the string "1,23" in this text field and move the focus to another component. 现在,我在此文本字段中输入字符串“ 1,23”,并将焦点移至另一个组件。 I would expect the string to disappear (like it does when i type "a" instead of "1,23") because it is obviously not a valid representation of a number when using Locale.US. 我希望该字符串消失(就像我键入“ a”而不是“ 1,23”时那样),因为使用Locale.US时,它显然不是数字的有效表示形式。 But instead the text in the text field is changed to "123". 而是将文本字段中的文本更改为“ 123”。

This is because the used NumberFormat is not strict when parsing and simply ignores the comma. 这是因为在解析时使用的NumberFormat并不严格,只是忽略了逗号。

Question : How can I tell NumberFormat to throw a ParseException in this case so the text field will be empty after moving the focus to another component? 问题 :在这种情况下,如何告诉NumberFormat抛出ParseException ,以便将焦点移到另一个组件后文本字段为空?

Test Code: 测试代码:

JDialog dialog = new JDialog();
JPanel panel = new JPanel(new BorderLayout());
dialog.getContentPane().add(panel);

NumberFormat nf = NumberFormat.getInstance(Locale.US);
JFormattedTextField textField = new JFormattedTextField(nf);
textField.setText("1,23");
panel.add(textField, BorderLayout.CENTER);
panel.add(new JButton("focus"), BorderLayout.EAST);

dialog.pack();
dialog.setVisible(true);

Move the focus from the text field to the button and the text will change to "123". 将焦点从文本字段移至按钮,文本将变为“ 123”。

I would suggest you to use regex and use the match fucntion like this: 我建议您使用正则表达式并使用匹配功能,如下所示:

matches("\\d+([.,])?")

Also if you will use Integer.parseInt(String) will throw an exception if it will be parsed or you can use Double.parseDouble(value) 另外,如果您将使用Integer.parseInt(String)将会引发异常,如果将其解析或可以使用Double.parseDouble(value)

实际上, Number只是Double的超类,因此您可以使用Double.parseDouble(...) ,然后自动拆箱就可以完成其余工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM