用javafx编写一个简单的加减计算器,计算器提供数据两个输入框、一个数据输出框、加按钮、减按钮、清除按钮。 输入框供用户输入参与加减计算的两个数值, 输出框设置为不可输入状态,由程序控制输出加减的结果。 加减按钮被点击时,将输入框的加减结果在输出框输出。 清除按钮被点击时,清除输入、输出框的所有内容。 清除按钮再添加一个鼠标进入和鼠标移出行为的处理,当鼠标进入清除按钮时,鼠标变成手的符号,鼠标移出时,鼠标变成箭头符号。
时间: 2024-01-21 13:17:18 浏览: 61
BMI-Calculator-JavaFX
以下是用JavaFX编写的加减计算器的代码:
```java
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
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 num1Field;
private TextField num2Field;
private TextField resultField;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("加减计算器");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10, 10, 10, 10));
grid.setVgap(5);
grid.setHgap(5);
num1Field = new TextField();
num1Field.setPromptText("输入第一个数");
GridPane.setConstraints(num1Field, 0, 0);
grid.getChildren().add(num1Field);
num2Field = new TextField();
num2Field.setPromptText("输入第二个数");
GridPane.setConstraints(num2Field, 0, 1);
grid.getChildren().add(num2Field);
Button addButton = new Button("加");
addButton.setOnAction(e -> calculate('+'));
GridPane.setConstraints(addButton, 1, 0);
grid.getChildren().add(addButton);
Button subButton = new Button("减");
subButton.setOnAction(e -> calculate('-'));
GridPane.setConstraints(subButton, 1, 1);
grid.getChildren().add(subButton);
resultField = new TextField();
resultField.setEditable(false);
resultField.setPromptText("计算结果");
GridPane.setConstraints(resultField, 0, 2);
GridPane.setColumnSpan(resultField, 2);
grid.getChildren().add(resultField);
Button clearButton = new Button("清除");
clearButton.setOnAction(e -> clear());
GridPane.setConstraints(clearButton, 0, 3);
grid.getChildren().add(clearButton);
clearButton.setOnMouseEntered(e -> {
clearButton.setStyle("-fx-cursor: hand;");
});
clearButton.setOnMouseExited(e -> {
clearButton.setStyle("-fx-cursor: arrow;");
});
Scene scene = new Scene(grid, 250, 150);
primaryStage.setScene(scene);
primaryStage.show();
}
private void calculate(char op) {
String num1Str = num1Field.getText();
String num2Str = num2Field.getText();
if (num1Str.isEmpty() || num2Str.isEmpty()) {
resultField.setText("请输入两个数值");
return;
}
try {
double num1 = Double.parseDouble(num1Str);
double num2 = Double.parseDouble(num2Str);
double result;
if (op == '+') {
result = num1 + num2;
} else {
result = num1 - num2;
}
resultField.setText(String.format("%.2f", result));
} catch (NumberFormatException e) {
resultField.setText("请输入正确的数值");
}
}
private void clear() {
num1Field.clear();
num2Field.clear();
resultField.clear();
}
public static void main(String[] args) {
launch(args);
}
}
```
运行该程序后,会显示一个简单的加减计算器界面,用户可以在两个输入框中输入数值,点击加、减按钮计算结果,点击清除按钮清空输入和输出框。当鼠标进入清除按钮时,鼠标会变成手的符号,当鼠标移出时,鼠标会变成箭头符号。
阅读全文