jeudi 13 décembre 2018

How to implement an observer design pattern?

I am trying to make a calculator, I have a GUI made with javafx, this has a button called calculate, a textfield which is used for the user to write input and an output textfield which shows the evaluation of the input. I have a controller class called controller and I also have the model class which the controller uses to perform calculations.

At the moment, my calculate method is in the controller, so when a user clicks calculate then the calculate method is called from controller.

I want to have my buttons and inputs in view class, and implement an observer pattern such that when a button is pressed it notifies the controller and sends the input text to the controller to calculate. But I am really confused on how to do this. Here is my code below:

NOTE: in FXML.fxml I have the fx:controller as Controller.

public class Controller {

  private static Model model;

  private static View view;

  @FXML 
  private TextField input;

  @FXML 
  private TextField output;    

  @FXML 
  private RadioButton button;

  public Controller(){
    view = new View();
    model = new Model();
    Thread viewT = new Thread(view);
    viewT.start();

  }

  @FXML
  public void calculate(){
    Integer i = (int) model.evaluate(input.getText()); 
    output.setText(i.toString());
  }

public class Model {

  public int evaluate(){//evaluates a string}
}

public class View extends Application implements Runnable{ 

  @Override
  public void start(Stage primaryStage) throws Exception {
    try {
      Parent root = . 
   FXMLLoader.load(View.class.getResource(("FXML.fxml")));
      primaryStage.setTitle("Calculator");
      Scene scene = new Scene(root,400,400);




     scene.getStylesheets().add(getClass()
     .getResource("application.css").toExternalForm());

      primaryStage.setScene(scene);
      primaryStage.show();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  @Override
  public void run() {
    try {
      launch(null);
    } catch (Exception e) {

    }
  }

}

Aucun commentaire:

Enregistrer un commentaire