I am currently working on a calculator in JavaFX and right now trying to implement keyboard input support.
For this I am trying to implement an EventHandler in the main
If you refactor the handler methods so they just determine the value they represent, then call another method, e.g.:
@FXML
private void handleDigitAction(ActionEvent event) {
String digit = ((Button) event.getSource()).getText();
handleDigit(digit) ;
}
public void handleDigit(String digit) {
if (state == State.FIRST || state == State.SECOND) {
oldText = displayField.getText();
} else {
oldText = "";
}
if ("0".equals(oldText) /*|| "0.0".equals(oldText)*/) {
displayField.setText(digit);
} else {
displayField.setText(oldText + digit);
}
if (state == State.EQUALED || state == State.FIRST) {
oldValue = Double.parseDouble(displayField.getText());
state = State.FIRST;
} else {
newValue = Double.parseDouble(displayField.getText());
state = State.SECOND;
}
}
then you can call the new method as needed:
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = loader.load();
FXMLDocumentController controller = loader.getController();
Scene scene_main = new Scene(root);
stage.setScene(scene_main);
stage.show();
scene_main.setOnKeyPressed(new EventHandler() {
@Override
public void handle(KeyEvent keyEvent) {
switch (keyEvent.getCode()) {
case DIGIT1:
controller.handleDigit("1");
break ;
case DIGIT2:
controller.handleDigit("2");
break ;
case DIGIT3:
controller.handleDigit("3");
break ;
case DIGIT4:
controller.handleDigit("4");
break ;
case DIGIT5:
controller.handleDigit("5");
break ;
case DIGIT6:
controller.handleDigit("6");
break ;
case DIGIT7:
controller.handleDigit("7");
break ;
case DIGIT8:
controller.handleDigit("8");
break ;
case DIGIT9:
controller.handleDigit("9");
break ;
}
}
}
);
}
and so on.