Lim
Lim

Reputation: 13

How to calculate number from two Jtextfield?

I'm designing a food ordering system which I need to get the input of cash that customer paid, then minus with the total price they need to pay to calculate the change. My JTextField can't show the correct answer for the change, it only show 0.0. I'm not sure what's the problem with my code. Hope that you all can help me. Appreciate your helps, thank you!

public Cash() {
    init();
    btnPay.addActionListener(this);
    setVisible(true);
}

public String returnChange1() {
    double change = 0.00 ;
    double custPay;
    String total = lblDisplayTotal.getText();
    double a=Double.parseDouble(total);

    if (!(txtCustPay.getText().isEmpty())){
        custPay = Double.parseDouble(txtCustPay.getText());
        change = custPay - a;
    }
    return String.valueOf(change);
}

public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(btnPay)) {
        returnChange1();
    }
}

public void init() {
    txtChange = new JTextField(returnChange1());
    txtChange.setSize(150, 30);
    txtChange.setLocation(150, 250);
    add(txtChange);
}

Upvotes: 1

Views: 141

Answers (1)

Alex
Alex

Reputation: 379

You are not assigning the function to the text field. In the button action, don't simply call the function, in this case what you should do is assign the function to the text field: txtChange.setText(returnChange1()), Also try to put a try and catch where you convert the text to double:

try{
    double a = Double.parseDouble(total);
}catch(NumberFormatException e){
    e.printStackTrace;
}

The above code is useful when the user mistakenly enters a character that is not a number.

public Cash() {
      
    init();
    btnPay.addActionListener(this);
    setVisible(true);

}

public String returnChange1() {

    double change = 0.00;
    double custPay;
    String total = lblDisplayTotal.getText();
    double a = Double.parseDouble(total);

    if (!(txtCustPay.getText().isEmpty())) {
        custPay = Double.parseDouble(txtCustPay.getText());
        change = custPay - a;
    }

    return String.valueOf(change);

}

public void actionPerformed(ActionEvent e) {

    if (e.getSource().equals(btnPay)) {
        txtChange.setText(returnChange1());
    }
}

public void init() {
    txtChange = new JTextField(returnChange1());
    txtChange.setSize(150, 30);
    txtChange.setLocation(150, 250);
    add(txtChange);
}

Upvotes: 1

Related Questions