这段代码是一个基本的 JavaFX 应用程序,用于创建一个简单的计算器应用。以下是对其进行调试和分析:
- 程序入口点为
start()
方法,该方法会在应用程序启动时被调用。
@Override
public void start(Stage primaryStage) {
// ...
}
- 在
start()
方法中,首先创建了文本框、按钮、标签等控件,并将它们添加到布局中。
TextField num1 = new TextField();
TextField num2 = new TextField();
TextField res = new TextField();
Button add = new Button("加");
Button sub = new Button("减");
Button mul = new Button("乘");
Button div = new Button("除");
Label symbol = new Label("+")
Label r = new Label("=");
HBox text = new HBox();
text.getChildren().addAll(num1, symbol, num2, r, res);
// ...
HBox botton = new HBox();
botton.getChildren().addAll(add, sub, mul, div);
// ...
BorderPane root = new BorderPane();
root.setTop(text);
root.setBottom(botton);
- 然后,在每个按钮上注册事件处理程序,以响应用户单击操作并执行相应的计算。
add.setOnAction(actionEvent -> {
symbol.setText("+");
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
res.setText(String.format("%.1f", n1 + n2));
});
sub.setOnAction(actionEvent -> {
symbol.setText("-");
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
res.setText(String.format("%.1f", n1 - n2));
});
mul.setOnAction(actionEvent -> {
symbol.setText("*");
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
res.setText(String.format("%.1f", n1 * n2));
});
div.setOnAction(actionEvent -> {
symbol.setText("/");
double n1 = Double.parseDouble(num1.getText());
double n2 = Double.parseDouble(num2.getText());
res.setText(String.format("%.1f", n1 / n2));
});
- 最后,在
start()
方法中创建了一个场景,并将布局添加到其中。
primaryStage.setScene(new Scene(root, 300, 73));
- 在
main()
方法中,调用launch()
方法启动 JavaFX 应用程序。
public static void main(String[] args) {
launch(args);
}
通过以上分析,我们可以看出这个程序使用了 JavaFX 的各种布局和控件来创建一个简单的计算器应用。每个按钮都有相应的事件处理程序,使得用户能够执行加、减、乘或除操作并得到结果。