NumberFormat解析不够严格 [英] NumberFormat parse not strict enough

查看:86
本文介绍了NumberFormat解析不够严格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Locale.US中有一个JFormattedTextField和一个NumberFormat.因此,小数点分隔符是点,分组分隔符是逗号.

I have a JFormattedTextField with a NumberFormat with Locale.US. So the decimal separator is the point and the grouping separator is the comma.

现在,我在此文本字段中输入字符串"1,23",并将焦点移至另一个组件.我希望该字符串消失(就像我键入"a"而不是"1,23"时那样),因为使用Locale.US时,它显然不是数字的有效表示形式.而是将文本字段中的文本更改为"123".

Now I type the string "1,23" in this text field and move the focus to another component. 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. But instead the text in the text field is changed to "123".

这是因为解析时使用的NumberFormat并不严格,只是忽略了逗号.

This is because the used NumberFormat is not strict when parsing and simply ignores the comma.

问题:在这种情况下,如何告诉NumberFormat抛出ParseException,以便在将焦点移至另一个组件后文本字段为空?

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?

测试代码:

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);

将焦点从文本字段移至按钮,文本将变为"123".

Move the focus from the text field to the button and the text will change to "123".

推荐答案

我建议您使用正则表达式并使用匹配功能,如下所示:

I would suggest you to use regex and use the match fucntion like this:

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

如果您将使用Integer.parseInt(String),则将抛出异常,如果将其解析或可以使用Double.parseDouble(value)

Also if you will use Integer.parseInt(String) will throw an exception if it will be parsed or you can use Double.parseDouble(value)

这篇关于NumberFormat解析不够严格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆