0

So, I need to pass parameter (ID) to new window which opens by clicking on TableView. Specifically I need to pass series Id parameter from MainContorller to TvShowsAboutController.

I'm opening TvShowsAboutController from MainController. Like this:

public void showSeriesInfo() {

    try { 

        BorderPane tvShows = (BorderPane) FXMLLoader.load(getClass().getResource("/seriesapp/javafx/tvShowAbout.fxml"));

        setCenterPane(tvShows);

    } catch (Exception e) { 
        e.printStackTrace(); 
    }  
}

But I don't know how to pass argument in TvShowsAvoutController class. If I create new TvShowsAboutController class then it crashes because it didn't load FXML file. I saw a similar problem on StackOverflow Passing Parameters JavaFX FXML but it didn't help much. I've tried with this, but no luck:

MainController class

    public void showSeriesInfo() {  
    try {   
        FXMLLoader loader = new FXMLLoader(getClass().getResource("/javafx/tvShowAbout.fxml"));
        TvShowAboutController controller = 
                loader.<TvShowAboutController>getController();
        controller.initData(showsTable.getSelectionModel().getSelectedItem().getShowid());

        BorderPane tvShows = (BorderPane) loader.load();

        setCenterPane(tvShows);

    } catch (Exception e) { 
        e.printStackTrace(); 
    }  
}

TvShowsAboutController class

@FXML
public void initialize(){

    showSeriesInfo();   
}
void initData(Integer showId) {
    this.seriesId = showId;
  }

P.S. Opening new pane works this way, but as i said I can not figure out how to pass the argument

Community
  • 1
  • 1
user3746480
  • 333
  • 5
  • 17

1 Answers1

2

The FXMLLoader, by default, creates an instance of the controller class that is specified in the FXML file. Therefore, the controller cannot be available until after it has loaded the FXML file. So you need to change the order of the method calls:

FXMLLoader loader = new FXMLLoader(getClass().getResource("/javafx/tvShowAbout.fxml"));

BorderPane tvShows = (BorderPane) loader.load();

TvShowAboutController controller = 
        loader.<TvShowAboutController>getController();
controller.initData(showsTable.getSelectionModel().getSelectedItem().getShowid());

Note this means that in TvShowAboutController, initialize() will be called before initData(), so nothing you do in initialize() can depend on the id being initialized. In this case, you should move anything that does depend on that to the initData() method. For example, you didn't show what showSeriesInfo() does, but you might need to do

// @FXML
// public void initialize() {
//     showSeriesInfo();
// }

void initData(int showId) {
    this.seriesId = showId ;
    showSeriesInfo();
}
James_D
  • 201,275
  • 16
  • 291
  • 322