diff --git a/01/src/Calculator.java b/01/src/Calculator.java new file mode 100644 index 0000000..a9c7447 --- /dev/null +++ b/01/src/Calculator.java @@ -0,0 +1,28 @@ +import javafx.application.Application; +import javafx.fxml.FXMLLoader; +import javafx.scene.Parent; +import javafx.scene.Scene; +import javafx.stage.Stage; + +import java.io.IOException; +import java.net.URL; + +public class Calculator extends Application { + + public static void main(String[] args) { + launch(args); + } + + @Override + public void start(Stage primaryStage) throws IOException { + //找到FXML文件 + URL url = getClass().getResource("CalculatorView.fxml"); + //用FXML创建树,得到根节点 + Parent root = FXMLLoader.load(url); + Scene scene = new Scene(root,282,330); + primaryStage.setTitle("计算器"); + primaryStage.setScene(scene); + primaryStage.show(); + } +} + diff --git a/01/src/CalculatorController.java b/01/src/CalculatorController.java new file mode 100644 index 0000000..0b57b61 --- /dev/null +++ b/01/src/CalculatorController.java @@ -0,0 +1,46 @@ +import javafx.event.ActionEvent; +import javafx.fxml.FXML; +import javafx.scene.control.Label; +import javafx.scene.control.Button; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; + +public class CalculatorController { + + @FXML + private Label display; // 用于显示计算结果的标签 + + private StringBuilder currentInput = new StringBuilder(); // 存储当前输入 + + public void handleButtonClick(ActionEvent actionEvent) { + String buttonText = ((Button) actionEvent.getSource()).getText(); // 获取被点击按钮的文本 + + if (buttonText.equals("C")) { + currentInput.setLength(0); // 清空输入 + display.setText("0"); + } else if (buttonText.equals("=")) { + calculateResult(); // 计算结果 + } else { + if (currentInput.length() < 10) { // 限制输入长度 + currentInput.append(buttonText); // 更新输入 + display.setText(currentInput.toString()); // 更新显示 + } + } + } + + private void calculateResult() { + ScriptEngineManager manager = new ScriptEngineManager(); + ScriptEngine engine = manager.getEngineByName("JavaScript"); // 使用JavaScript引擎进行计算 + try { + Object result = engine.eval(currentInput.toString()); // 计算结果 + display.setText(result.toString()); // 更新显示 + currentInput.setLength(0); // 清空当前输入 + currentInput.append(result.toString()); // 将结果设置为下一个计算的输入 + } catch (ScriptException e) { + display.setText("Error"); // 处理错误 + currentInput.setLength(0); // 清空输入 + } + } +} diff --git a/01/src/CalculatorView.fxml b/01/src/CalculatorView.fxml new file mode 100644 index 0000000..90c6f6d --- /dev/null +++ b/01/src/CalculatorView.fxml @@ -0,0 +1,37 @@ + + + + + + + + +
+ +
+
+ + +