请写一个JAVAfx的简易计算器
时间: 2024-04-18 18:31:36 浏览: 111
当然可以!下面是一个简单的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.stage.Stage;
public class SimpleCalculator extends Application {
private TextField display;
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Simple Calculator");
GridPane grid = new GridPane();
grid.setPadding(new Insets(10));
grid.setHgap(5);
grid.setVgap(5);
display = new TextField();
display.setPrefWidth(200);
display.setEditable(false);
grid.add(display, 0, 0, 4, 1);
String[] buttons = {
"7", "8", "9", "/",
"4", "5", "6", "*",
"1", "2", "3", "-",
"0", ".", "=", "+"
};
int row = 1;
int col = 0;
for (String button : buttons) {
Button btn = new Button(button);
btn.setPrefSize(50, 50);
btn.setOnAction(e -> handleButtonClick(button));
grid.add(btn, col, row);
col++;
if (col > 3) {
col = 0;
row++;
}
}
Scene scene = new Scene(grid);
primaryStage.setScene(scene);
primaryStage.show();
}
private void handleButtonClick(String button) {
if (button.equals("=")) {
evaluateExpression();
} else {
display.setText(display.getText() + button);
}
}
private void evaluateExpression() {
String expression = display.getText();
try {
double result = Calculator.evaluate(expression);
display.setText(Double.toString(result));
} catch (Exception e) {
display.setText("Error");
}
}
public static void main(String[] args) {
launch(args);
}
}
```
注意:这只是一个简单的示例,实际上并没有实现完整的计算功能。你需要自己实现 Calculator 类,用于计算表达式的结果。你可以根据需要进行扩展和修改。希望对你有所帮助!
阅读全文