NumberFormat解析不够严格

编程入门 行业动态 更新时间:2024-10-06 18:32:57
本文介绍了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解析不够严格

本文发布于:2023-11-23 06:53:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620510.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NumberFormat

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!