繁体   English   中英

如何正确地从awt文本字段中读取数字?

[英]How do I properly read numbers from awt textfields?

我已经为正在执行的模拟项目编写了GUI,例如,在窗口的事件处理代码中,

private void timestepKeyTyped(java.awt.event.KeyEvent evt) {
    String text = timestep.getText();
    AMEC.steptime = Integer.parseInt(text);
}

在这里,我想将任何键入字段timestep的输入分配给AMEC.steptime。 我对所有文本字段都执行此操作。

但是,传递这些参数时,我的模拟无法正常运行,并且在调试后,我发现只有第一个字符被解析为int。 例如,如果我键入“ 31”,则分配给AMEC.steptime的值将变为3而不是31。

我该如何解决?

您面临的问题是您正在使用KeyListener 只是不使用它,请使用ActionListener并在按Enter时执行actionPerformed 然后,您可以放置​​相同的代码,就像魅力一样运行。

使用秋千而不是awt。

示例如何使用它:

首先导入:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JTextField;

然后在代码中的某个地方

JTextField textfield = new JTextField();
        textfield.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                JTextField timestep =(JTextField) e.getSource();// you could use this or just your variable.
                String text = timestep.getText();
                AMEC.steptime = Integer.parseInt(text);
            }

        });

附带说明,您可能只希望在此文本字段中使用数字值。 阅读更多有关如何在上一个问题中做到这一点的信息。 将JTextField输入限制为整数

暂无
暂无

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

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