Search code examples
javajtextfield

on button click update jttextfield and calculate with newly entered value?


In my Java GUI there are 4 JTextFields. The goal is to enter default values for 3 textfields (example .8 in code below) and calculate the value and display the calculation into the 4th textfield. The user should then be able to change the values of the numbers within the JTextField and then press the calculate button again to get the new values to recalculate and display them.

Problem: when the JTextfields are edited and the calculate button is pressed it does not calculate with the new numbers but instead with the old initial values.

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);
}

I have checked several posts and tried:

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

Using JTextField for user input

for the basics. However whenever trying to adapt it to my code eclipse returns various errors.


Solution

  • try using This code.

    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));
    
    }
    

    }