Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX 1 FXML File with Multiple Different Controllers?

There are two different stages in my application that are help screens that use the same FXML file. Rather than create 2 FXML files, I would like to use just one and have two controllers that call the same fxml.

The only problem is that the Controller is assigned in the FXML file. So, is there a way to change the assigned controller with code in the Controller class itself?

I'd really like to avoid duplicating an FXML file just to change the Controller in each. Thanks in advance.


like image 649
Matt Avatar asked Apr 12 '13 06:04

Matt


1 Answers

You can remove the fx:controller="" assignment from the FXML file and assign the controller via the FXMLLoader during the load.

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("Your.fxml"));
fxmlLoader.setController(this);

try
{
    fxmlLoader.load();
}
catch (IOException exception)
{
    throw new RuntimeException(exception);
}

Check out the Introduction to FXML section on custom components.

like image 141
OttPrime Avatar answered Nov 27 '22 05:11

OttPrime