Reputation: 53
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));
Upvotes: 1
Views: 1069
Reputation: 158
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:
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));
Upvotes: 1