1

I came across some very strange behaviour a couple of times every time forgetting the trick.

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = loader.load();
GuiController controller = loader.getController();

Now the controller is not null.

However, after I do this...

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = loader.load(getClass().getResource("view/window.fxml"));
GuiController controller = loader.getController();

The controller is now null.

I understand that the loader somehow looses his grip on location? I would very much appreciate somebody telling me that this is an expected behaviour and explain me why.

Please note that is looked quite a bit after post concerning this problem found nothing, and discovered the solution only after 2h of experimentation, so please don't link me up with similar looking questions.

ZbyszekKr
  • 512
  • 4
  • 15

1 Answers1

1

The FXMLLoader method load(URL) is a static method. So your second code block is equivalent to (compiles to)

FXMLLoader loader = new FXMLLoader();
// I assume you mean loader, not fxmlLoader, in the next line:
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = FXMLLoader.load(getClass().getResource("view/window.fxml"));
GuiController controller = loader.getController();

In other words, you never invoke load(...) on loader: hence loader never parses the FXML and never instantiates the controller.

In your first code block, you invoke the no-arg load() method, which is an instance method.

James_D
  • 201,275
  • 16
  • 291
  • 322
  • Haven't noticed the `static` keyword in the documentation. Thank you very much. :) Lost quite a lot of my evening for that. – ZbyszekKr Nov 12 '15 at 22:25
  • For some reason I had my warning suppressed for this class... After switching them back on it performed as you said it would. Thanks. – ZbyszekKr Nov 12 '15 at 22:30
  • Most IDEs will give you a warning if you call a static method from a reference. – James_D Nov 12 '15 at 22:38