-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCalculator.java
More file actions
86 lines (71 loc) · 2.67 KB
/
Calculator.java
File metadata and controls
86 lines (71 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Calculator extends Application {
private TextField firstOperand;
private TextField secondOperand;
private TextField result;
@Override
public void start(Stage primaryStage) {
GridPane grid = new GridPane();
grid.setAlignment(Pos.CENTER);
grid.setHgap(10);
grid.setVgap(10);
firstOperand = new TextField();
secondOperand = new TextField();
result = new TextField();
result.setEditable(false);
Label firstOperandLabel = new Label("First Operand:");
Label secondOperandLabel = new Label("Second Operand:");
Label resultLabel = new Label("Result:");
Button addButton = new Button("Add");
Button subtractButton = new Button("Subtract");
Button clearButton = new Button("Clear");
grid.add(firstOperandLabel, 0, 0);
grid.add(firstOperand, 1, 0);
grid.add(secondOperandLabel, 0, 1);
grid.add(secondOperand, 1, 1);
grid.add(resultLabel, 0, 2);
grid.add(result, 1, 2);
HBox hBox = new HBox(10);
hBox.setAlignment(Pos.CENTER);
hBox.getChildren().addAll(addButton, subtractButton, clearButton);
grid.add(hBox, 1, 3);
addButton.setOnAction(e -> {
try {
double a = Double.parseDouble(firstOperand.getText());
double b = Double.parseDouble(secondOperand.getText());
result.setText(String.valueOf(a + b));
} catch (NumberFormatException ex) {
result.setText("Invalid Input");
}
});
subtractButton.setOnAction(e -> {
try {
double a = Double.parseDouble(firstOperand.getText());
double b = Double.parseDouble(secondOperand.getText());
result.setText(String.valueOf(a - b));
} catch (NumberFormatException ex) {
result.setText("Invalid Input");
}
});
clearButton.setOnAction(e -> {
firstOperand.setText("");
secondOperand.setText("");
result.setText("");
});
Scene scene = new Scene(grid, 350, 200);
primaryStage.setTitle("Simple Calculator");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}