如何将JTextField的输入转换为double.输入值来自用户 [英] How can I convert input from JTextField into double. Input value is from user
本文介绍了如何将JTextField的输入转换为double.输入值来自用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用JTextField的输入并将其转换为double',因为我要在程序中的数学公式中使用该输入.但是当我尝试运行代码时,它给出了错误..我认为我解析的方法有误.任何帮助吗?谢谢!
I'm trying to use an input from JTextField and turn it into double 'coz I'm gonna use the input in a mathematical formula in my program.. but when I try to run the codes, it gives an error.. I think I got the wrong way of parsing.. ANY HELP? Thanks!
xLabel = new JLabel("Subject");
xTF = new JTextField(4);
xTF.addKeyListener(new KeyHandler());
xString = xTF.getText();
xDouble = Double.parseDouble(xString);
推荐答案
- 不要在文本组件上使用
KeyListener
,使用DocumentFilter
,请查看文档过滤器示例以获取更多详细信息 - 您可以改用
InputVerifier
.有关更多详细信息,请参见验证输入 - 您可以改用
JFormmattedField
或JSpinner
.请参见如何使用格式化的文本字段和
- Don't use
KeyListener
on text components, use aDocumentFilter
, take a look at Implementing a Document Filter and DocumentFilter Examples for more details - You could use a
InputVerifier
instead. See Validating Input for more details - You could use a
JFormmattedField
orJSpinner
instead. See How to Use Formatted Text Fields and How to Use Spinners for more details
很难说出来,但请记住,您是在事件驱动的环境中进行操作的,除非用户执行某些操作,否则您不应该试图获取字段的值
It's difficult to tell, but remember, you're operating in an event driven environment, until the user does something, you should not be trying to get the value of a field
这篇关于如何将JTextField的输入转换为double.输入值来自用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文