0

I am using javafx combined with FXML. I want to apply the MVC pattern. For that I want my Model.java class to be the model, which launches the View.fxml and the controller of that view would be viewController.java.

I need to bring Model.java and Controller.java to communicate at some point. So let's say ViewController.java looks this way:

public class ViewController implements Initializable {

    private String parameter = "hello";
    @FXML
    private Label label;

    @FXML
    private Accordion acccord;

    public String getParemeter() {
        return this.parameter;
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
    }    

}

ViewController has a private string and its own methods.

And Model.java :

public class Model extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(getClass().getResource("View.fxml") );

        Parent root = loader.load();  // Here the View is loaded and the Contoller is created along.

        loader.getController(); // ?
        //Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));

        Scene scene = new Scene(root);

        stage.setScene(scene);
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

How can I access the ViewContoller parameters / methods (such as getPamareter() ) ? I tried to get the controller with loader.getController() but it returns a generic type, what should I do with it, provided it has something to do with it? I went to the oracle documentation but I am not quite sure to understan, does getController() return an instance of my ViewController.java ?

HOw can I access the Model from the ViewController? For instance a buton is triggered, the vieController would update a value in Model.java.

kaligne
  • 3,098
  • 9
  • 34
  • 60
  • 2
    Just write `ViewController controller = loader.getController();` . `FXMLLoader` will cast the controller instance to the type of the assigned variable. – FuryFart Jul 17 '14 at 12:37
  • Perfect! I figured that loader.getController() should be called after loader.load(), otherwise it would return null. I guess I just need to create a setter to pass a reference of the model to the view. MAny thanks! – kaligne Jul 17 '14 at 12:55

0 Answers0