2

I have some generic FXML with lots of components but lets say it is a textArea for simplicity.

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.TextArea?>


<TextArea fx:id="test" prefHeight="200.0" prefWidth="200.0" promptText="test data" xmlns="http://javafx.com/javafx/8.0.101" xmlns:fx="http://javafx.com/fxml/1" />

And on this textArea you can see that it has an id of "test".

So my question is can you could reuse this FXML in more than one controller?

My initial thought was through an Generic Controller as seen below:

public abstract class GenericController {
    Program program = Program.getInstance();
    @FXML TextArea test;


    @FXML
    abstract void  initialize();
    abstract void setData();




}

And point the FXML to the GenericController. And then extend it in a more specific controller. But i just get an LoadExceptionError which errors at the fx:controller="sample.Controllers.GenericController".

audittxl
  • 41
  • 1
  • 12

1 Answers1

3

Just don't specify the controller in the FXML file, i.e. remove the fx:controller attribute entirely. Then set the controller when you load the FXML:

FXMLLoader loader = new FXMLLoader(getClass().getResource("path/to/generic.fxml"));
GenericController controller = new SpecificControllerImplementation();
loader.setController(controller);
Parent root = loader.load();
James_D
  • 201,275
  • 16
  • 291
  • 322
  • There are more advanced things you can do using a controller factory, (which, for example, you could combine with a dependency injection framework) if you need, but it sounds like this would be enough for what you need. – James_D Feb 17 '17 at 18:40
  • Just tried this and i am still getting `javafx.fxml.LoadException: No controller specified.` – audittxl Feb 17 '17 at 18:46
  • @audittxl Then you are doing something wrong. You're calling the no-argument `load()` method, right, not the static `load(URL)` method? – James_D Feb 17 '17 at 18:47
  • my mistake i did not compile the code **doh**! And ran the old code! – audittxl Feb 17 '17 at 18:49
  • i am now getting a javafx.scene.layout.BorderPane cannot be cast to javafx.fxml.FXMLLoader error?! – audittxl Feb 17 '17 at 18:51
  • @audittxl Again, that means you are doing something wrong (maybe `FXMLLoader.load(...)` instead of `new FXMLLoader(...)`). Use the code I posted, not some garbled version of it. – James_D Feb 17 '17 at 18:56
  • you are a genius! – audittxl Feb 17 '17 at 18:59