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. 创建文本框 num1、num2 和 res,以及按钮 add、sub、mul 和 div。
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("除");

在这里,我们使用 TextField 控件来创建输入框,并使用 Button 控件来创建四个功能按钮。

  1. 创建标签 symbol 和 r,用于显示计算符号和等号。
Label symbol = new Label("+");
Label r = new Label("=");

在这里,我们使用 Label 控件来创建两个标签节点。其中一个用于显示计算符号(+、-、* 或 /),另一个用于显示等号(=)。

  1. 使用 HBox 和 BorderPane 布局将各个控件组合在一起。
HBox text = new HBox();
text.getChildren().addAll(num1, symbol, num2, r, res);
text.setAlignment(Pos.CENTER);
text.setPadding(new Insets(10, 10, 10, 10));
text.setSpacing(10);

HBox botton = new HBox();
botton.getChildren().addAll(add, sub, mul, div);
botton.setAlignment(Pos.CENTER);
botton.setPadding(new Insets(3, 3, 3, 3));
botton.setSpacing(3);

BorderPane root = new BorderPane();
root.setTop(text);
root.setBottom(botton);

在这里,我们使用 HBoxBorderPane 两种布局来将各个控件组合在一起。其中,HBox 布局用于将输入框、标签和结果框放在同一行中,并设置了一些间距和对齐方式;而 BorderPane 布局用于将按钮节点放在底部区域。

  1. 当用户点击加、减、乘或除按钮时,获取 num1 和 num2 中的值,并根据所选操作进行相应的计算。
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));
});

在这里,我们为每个按钮添加了一个事件处理程序(即 setOnAction() 方法),当用户单击该按钮时,将执行相应的代码。其中,我们首先获取输入框中的两个数值,并根据所选操作进行计算。最后,我们使用 String.format() 方法来格式化结果并将其显示在结果框中。

  1. 将计算结果显示在 res 文本框中。
res.setText(String.format("%.1f", n1 + n2));

在这里,我们使用 setText() 方法将计算结果显示在结果框中,并使用 String.format() 方法来保留一位小数。

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

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

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

联系我们

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

微信号:3007537140

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

关注我们
x

注册

已经有帐号?