commit
d37afe4c17
@ -1,100 +0,0 @@
|
||||
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.VBox;
|
||||
import javafx.stage.Stage;
|
||||
|
||||
public class Calculator extends Application {
|
||||
private TextField display;
|
||||
private double result = 0;
|
||||
private String lastCommand = "=";
|
||||
private boolean start = true;
|
||||
|
||||
@Override
|
||||
public void start(Stage primaryStage) {
|
||||
// 创建显示区域
|
||||
display = new TextField("0");
|
||||
display.setEditable(false);
|
||||
display.setPrefColumnCount(15);
|
||||
|
||||
// 创建按钮
|
||||
GridPane grid = new GridPane();
|
||||
grid.setPadding(new Insets(10));
|
||||
grid.setHgap(10);
|
||||
grid.setVgap(10);
|
||||
|
||||
// 按钮布局
|
||||
String[][] buttonLayout = {
|
||||
{"7", "8", "9", "/"},
|
||||
{"4", "5", "6", "*"},
|
||||
{"1", "2", "3", "-"},
|
||||
{"0", ".", "=", "+"}
|
||||
};
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
for (int j = 0; j < 4; j++) {
|
||||
Button button = new Button(buttonLayout[i][j]);
|
||||
button.setOnAction(e -> processButtonPress(button.getText()));
|
||||
grid.add(button, j, i);
|
||||
}
|
||||
}
|
||||
|
||||
// 创建主布局
|
||||
VBox root = new VBox();
|
||||
root.setPadding(new Insets(10));
|
||||
root.setSpacing(10);
|
||||
root.getChildren().addAll(display, grid);
|
||||
|
||||
// 创建场景
|
||||
Scene scene = new Scene(root, 300, 300);
|
||||
|
||||
// 设置舞台
|
||||
primaryStage.setTitle("简易计算器");
|
||||
primaryStage.setScene(scene);
|
||||
primaryStage.show();
|
||||
}
|
||||
|
||||
private void processButtonPress(String command) {
|
||||
if (command.matches("[0-9]")) {
|
||||
if (start) {
|
||||
display.setText(command);
|
||||
start = false;
|
||||
} else {
|
||||
display.setText(display.getText() + command);
|
||||
}
|
||||
} else if (command.equals(".")) {
|
||||
if (start) {
|
||||
display.setText("0.");
|
||||
start = false;
|
||||
} else if (!display.getText().contains(".")) {
|
||||
display.setText(display.getText() + ".");
|
||||
}
|
||||
} else {
|
||||
calculate(Double.parseDouble(display.getText()));
|
||||
lastCommand = command;
|
||||
start = true;
|
||||
}
|
||||
}
|
||||
|
||||
private void calculate(double n) {
|
||||
if (lastCommand.equals("+")) {
|
||||
result += n;
|
||||
} else if (lastCommand.equals("-")) {
|
||||
result -= n;
|
||||
} else if (lastCommand.equals("*")) {
|
||||
result *= n;
|
||||
} else if (lastCommand.equals("/")) {
|
||||
result /= n;
|
||||
} else {
|
||||
result = n;
|
||||
}
|
||||
display.setText(String.format("%.0f", result));
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
launch(args);
|
||||
}
|
||||
}
|
Loading…
Reference in new issue