【问题标题】:on button click update jttextfield and calculate with newly entered value?在按钮上单击更新 jttextfield 并使用新输入的值进行计算?
【发布时间】:2015-12-14 15:17:37
【问题描述】:

在我的 Java GUI 中有 4 个JTextFields。目标是输入 3 个文本字段的默认值(下面代码中的示例 0.8)并计算值并将计算结果显示到第 4 个文本字段中。然后,用户应该能够更改JTextField 中数字的值,然后再次按下计算按钮以获取新值以重新计算并显示它们。

问题:当编辑 JTextfields 并按下计算按钮时,它不会使用新数字而是使用旧的初始值进行计算。

JTextField S = new JTextField();
S.setText(".8");
String Stext = S.getText();
final double Snumber = Double.parseDouble(Stext);
.... *same setup for Rnumber*
.... *same setup for Anumber*
....
JButton btnCalculate_1 = new JButton("Calculate");
btnCalculate_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) 
{
  int valuec = (int) Math.ceil(((Snumber*Rnumber)/Anumber)/8);
  String stringValuec = String.valueOf(valuec);
NewTextField.setText(stringCalc);
}

我检查了几个帖子并尝试过:

How Do I Get User Input from a TextField and Convert it to a Double?

Using JTextField for user input

基础知识。但是,每当尝试使其适应我的代码时,eclipse 都会返回各种错误。

【问题讨论】:

    标签: java jtextfield


    【解决方案1】:

    使用S.getText() actionPerformed() 方法。 actionperformed 块内的代码在按钮按下时被调用,而其外的代码不受影响。 因此,一旦您运行代码并向文本字段插入值,它就会分配 a 值,但是当您更改值并按下计算按钮时它不会改变相同

    【讨论】:

    • 我在actionperformed() 中添加了S.getText()。然后它说 make S “final” 我做了。然而,这并没有改变任何东西。它仍然使用默认值进行计算。
    • 不要将 S 定为最终版本。使其成为全球 Jtextfeild
    • 谢谢...不过仍然没有任何改变。
    • 你为什么在这里使用final:“final double Snumber = Double.parseDouble(Stext);”?最终变量的值不能改变
    • 我这样做是因为否则我的程序无法运行,它只会返回多个错误。
    【解决方案2】:

    尝试使用此代码。

    class a extends JFrame implements ActionListener
    {
    JTextField t1,t2,t3;
    a()
    {
    
        setLayout(null);
        t1 = new JTextField();
        t2 = new JTextField();
        t3 = new JTextField();
        JButton B1 = new JButton("Calculate");
    
        t3.setEditable(false);
    
        t1.setBounds(10,10,100,30);
        t2.setBounds(10,40,100,30);
        t3.setBounds(10,70,100,30);
    
        B1.setBounds(50, 110, 80, 50);
    
        add(t1);
        add(t2);
        add(t3);
        add(B1);
    
        B1.addActionListener(this);
    
        setSize(200,200);
        setVisible(true);
    }
    public static void main(String args[])
        {
            new a();
        }
    @Override
    public void actionPerformed(ActionEvent e) 
    {
        double Snumber = Double.parseDouble(t1.getText());
        double Rnumber = Double.parseDouble(t2.getText());
        double Anumber = Snumber+Rnumber;
        t3.setText(String.valueOf(Anumber));
    
    }
    

    }

    【讨论】:

    • 根据你的功能改变它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多