I am working on a Simple JavaFX Calculator for school, I am stuck on putting together an Action Event that take the input from both text fields, the radio button that is selected, and the perform that event when the calculate button is pressed.
btnCalc.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent e) {
}
});
}
public void calculation(ActionEvent e) {
int num1, num2, answer;
num1 = Integer.parseInt(tfNum1.getText());
num2 = Integer.parseInt((tfNum2.getText()));
if (rbAdd.isSelected()) {
answer = num1 num2;
} else if (rbSubtract.isSelected()) {
answer = num1 - num2;
} else if (rbMultiply.isSelected()) {
answer = num1 * num2;
} else {
answer = num1 / num2;
}
tfAns.setText(String.valueOf(answer));
CodePudding user response:
The function btnCalc.setOnAction() asks for an EventHandler as parameter. What this will do is every time you press the button, it will execute the handle() method of that EventHandler (which is empty in your case). You can solve that in 3 different ways:
- You call your calculation(ActionEvent e) function in the handle(ActionEvent e) function of the EventHandler (if you do this, you can delete the ActionEvent parameter from calculation().
- You copy your code from calculation(ActionEvent e) into handle(ActionEvent e)
- The best option here probably is to use a lambda. When an interface has just 1 function, you don't have to "make" an object of the interface but you can just give the function in the following way:
btnCalc.setOnAction(e -> calculation());
In this case you can also remove the ActionEvent e from the parameters of calculation().
So the total code would look like this:
btnCalc.setOnAction(e -> calculation());
public void calculation() {
int num1, num2, answer;
num1 = Integer.parseInt(tfNum1.getText());
num2 = Integer.parseInt((tfNum2.getText()));
if (rbAdd.isSelected()) {
answer = num1 num2;
} else if (rbSubtract.isSelected()) {
answer = num1 - num2;
} else if (rbMultiply.isSelected()) {
answer = num1 * num2;
} else {
answer = num1 / num2;
}
tfAns.setText(String.valueOf(answer));