import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.event.ActionEvent; public class CalculatorController { @FXML private TextField inputField; @FXML private TextField inputField1; // 用于显示计算记录 private double firstNumber = 0; private String operator = ""; private boolean isOperationClicked = false; @FXML protected void handleNumberAction(ActionEvent event) { Button button = (Button) event.getSource(); String number = button.getText(); if (isOperationClicked) { inputField.clear(); isOperationClicked = false; } inputField.setText(inputField.getText() + number); } @FXML protected void handleAddAction(ActionEvent event) { performOperation("+"); } @FXML protected void handleSubtractAction(ActionEvent event) { performOperation("-"); } @FXML protected void handleMultiplyAction(ActionEvent event) { performOperation("*"); } @FXML protected void handleDivideAction(ActionEvent event) { performOperation("/"); } @FXML protected void handleModulusAction(ActionEvent event) { performOperation("%"); } private void performOperation(String op) { firstNumber = Double.parseDouble(inputField.getText()); operator = op; isOperationClicked = true; } @FXML protected void handleEqualAction(ActionEvent event) { double secondNumber = Double.parseDouble(inputField.getText()); double result = 0; switch (operator) { case "+": result = firstNumber + secondNumber; break; case "-": result = firstNumber - secondNumber; break; case "*": result = firstNumber * secondNumber; break; case "/": if (secondNumber != 0) { result = firstNumber / secondNumber; } else { inputField.setText("Error"); return; } break; case "%": result = firstNumber % secondNumber; break; default: return; } inputField.setText(String.valueOf(result)); recordOperation(firstNumber, secondNumber, result); } private void recordOperation(double a, double b, double result) { String operation = a + " " + operator + " " + b + " = " + result; inputField1.setText(inputField1.getText() + "\n" + operation); } @FXML protected void handleClearAction(ActionEvent event) { inputField.clear(); firstNumber = 0; operator = ""; isOperationClicked = false; } @FXML protected void handleClearsAction(ActionEvent event) { inputField1.clear(); } @FXML protected void handlePointAction(ActionEvent event) { if (!inputField.getText().contains(".")) { inputField.setText(inputField.getText() + "."); } } @FXML protected void handleRemoveAction(ActionEvent event) { inputField1.clear(); } }