我是初学程序员并且我学到了足够多的java,现在我的目标是使用JavaFX为gui创建一个计算器并尽可能地使用oop,以便在实践中,其他人很容易修改程序,我在添加按钮并想要将setOnAction
方法应用于它时遇到问题,我想要一个单独的类来处理按钮的事件,但我不能理解如何使用它特殊方法
这是Gui
类:
package calculator;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
public class Gui extends Application {
InputHandler inputhandler = new InputHandler();
Button add = new Button();
@Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("HackCalc");
add.setText("+");
add.setOnAction(inputhandler);
StackPane layout = new StackPane();
layout.getChildren().add(add);
Scene scene = new Scene(layout, 330, 500);
primaryStage.setScene(scene);
primaryStage.show();
}
}
正如你所看到的,我已经创建了InputHandler
类的一个实例,我会告诉你并将它传递给setOnAction
但是它从来没有用过,我有一个令人沮丧的{{ 1}}错误。
现在,NoSuchMethodException
类:
InputManager
答案 0 :(得分:3)
首先InputHandler
延伸Gui
因为设计而没有意义,因为"是{{}之间的" 关系1}}和InputHandler
/ Gui
。
您最好使用anonymus class / lambda表达式作为事件处理程序,并且还要删除对按钮的检查,但使用不同的事件处理程序。这样你就可以摆脱所有的Application
检查......
有意义的是从计算器逻辑中分离视图,使GUI独立于计算器逻辑。
示例强>
if (source == someButton)
public class Calculator {
private final ObservableList<String> formulaParts = FXCollections.observableArrayList();
private final ObservableList<String> formulaPartsUnmodifiable = FXCollections.unmodifiableObservableList(formulaParts);
private final ReadOnlyStringWrapper operandString = new ReadOnlyStringWrapper();
private Integer operand;
private Integer previousOperand;
private IntBinaryOperator operator;
private boolean operandModifiable = true;
/** previous input elements as Strings */
public ObservableList<String> getFormulaParts() {
return formulaPartsUnmodifiable;
}
public final String getOperand() {
return this.operandString.get();
}
/** property contains current input as String */
public final ReadOnlyStringProperty operandProperty() {
return this.operandString.getReadOnlyProperty();
}
public void addDigit(byte digit) {
if (operandModifiable) {
operand = operand == null ? digit : operand * 10 + digit;
operandString.set(Integer.toString(operand));
}
}
public void addBinaryOperator(IntBinaryOperator operator) {
if (operand != null) {
if (previousOperand != null) {
evaluate();
}
previousOperand = operand;
operand = null;
operandString.set("");
formulaParts.setAll(Integer.toString(previousOperand), operator.toString());
this.operator = operator;
operandModifiable = true;
}
}
public void evaluate() {
if (operand != null && operator != null) {
int result = operator.applyAsInt(previousOperand, operand);
formulaParts.clear();
operandString.set(Integer.toString(result));
operandModifiable = false;
previousOperand = null;
operand = result;
}
}
}
public class BinaryPlusOperator implements IntBinaryOperator {
@Override
public int applyAsInt(int left, int right) {
return left + right;
}
@Override
public String toString() {
return "+";
}
}