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.

1
  • You presumably mean loader, not fxmlLoader in both calls to setLocation(...). Commented Nov 12, 2015 at 22:21

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Haven't noticed the static keyword in the documentation. Thank you very much. :) Lost quite a lot of my evening for that.
For some reason I had my warning suppressed for this class... After switching them back on it performed as you said it would. Thanks.
Most IDEs will give you a warning if you call a static method from a reference.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.