如何将JTextField的输入转换为double.输入值来自用户 [英] How can I convert input from JTextField into double. Input value is from user

查看:69
本文介绍了如何将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);

推荐答案

  1. 不要在文本组件上使用 KeyListener ,使用 DocumentFilter ,请查看文档过滤器示例以获取更多详细信息
  2. 您可以改用 InputVerifier .有关更多详细信息,请参见验证输入
  3. 您可以改用 JFormmattedField JSpinner .请参见如何使用格式化的文本字段
  1. Don't use KeyListener on text components, use a DocumentFilter, take a look at Implementing a Document Filter and DocumentFilter Examples for more details
  2. You could use a InputVerifier instead. See Validating Input for more details
  3. You could use a JFormmattedField or JSpinner 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屋!

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