ZBLOG

package com.example.calculator; import javafx.application.Application;//程序入口点 import javafx.geometry.Insets;//定义布局边框的间距 import javafx.geometry.Pos;//定义子节点在容器内的对齐方式 import javafx.scene.Scene;//场景,代表应用程序窗口上的内容 import javafx.scene.control.Button;//通...

这段代码是一个基本的 JavaFX 应用程序,用于创建一个简单的计算器应用。以下是对其进行调试和分析:

  1. 程序入口点为 start() 方法,该方法会在应用程序启动时被调用。
@Override
public void start(Stage primaryStage) {
    // ...
}
  1. 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);
  1. 然后,在每个按钮上注册事件处理程序,以响应用户单击操作并执行相应的计算。
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));
});
  1. 最后,在 start() 方法中创建了一个场景,并将布局添加到其中。
primaryStage.setScene(new Scene(root, 300, 73));
  1. main() 方法中,调用 launch() 方法启动 JavaFX 应用程序。
public static void main(String[] args) {
    launch(args);
}

通过以上分析,我们可以看出这个程序使用了 JavaFX 的各种布局和控件来创建一个简单的计算器应用。每个按钮都有相应的事件处理程序,使得用户能够执行加、减、乘或除操作并得到结果。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=4985

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?