0

Alright, I have been reading a lot of stackoverflow posts about how to PROPERLY create a JavaFX application with two windows that share data between them I can't find any clear solution. This is my current solution, basically creating a reference to the other controller which is really bad practice.

Would it be good practice to create a Model that is shared between the two controllers? If so how would I inject the Model object into the controllers when they dont have any constructors?

public class ControllerOne implements Initializable {

     @FXML private TextField textField;

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

     }        


    @FXML    
    private void handleButtonAction(ActionEvent event) {

        if(textField.getText().equals("")){

        }
        else{
            System.out.println(textField.getText());
            String itemNumber = textField.getText();

            Main.getControllerTwo().setLabel(itemNumber);        
            textField.setText("");
            textField.requestFocus();
        }

    }  
}

Second window

public class ControllerTwo implements Initializable {
    @FXML 
    private Label itemLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // TODO Auto-generated method stub

    }



    public void setLabel(String itemNumber){
        itemLabel.setText(itemNumber);
    }

    public Label getLabel(){
        return itemLabel;
    }



}
Rem
  • 73
  • 1
  • 8
  • 1
    Yes and https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml – fabian Jan 23 '18 at 16:57
  • So basically the idea is to create a reference to the controllers in the Main class and pass a reference of the Model from there to the controllers? – Rem Jan 23 '18 at 16:59
  • 1
    @Rem Correct. For a more complex app, it might be beneficial to [incorporate a dependency injection framework](https://stackoverflow.com/questions/40539310/dependency-injection-and-javafx) to manage the dependencies between the controllers and a model. – James_D Jan 23 '18 at 17:09
  • 1
    @Rem Also note "controllers ... don't have any constructors" isn't necessarily true. You can create the controller instances yourself and call `setController` on the `FXMLLoader` (as in the link in the first comment); or you can use a controller factory that creates the controller instance by calling any constructor you choose. Either of these techniques would allow the controller class to have arbitrary constructors defined. – James_D Jan 23 '18 at 17:55

0 Answers0