Kachna
Kachna

Reputation: 2961

why these two codes give different outputs

Given the following codes:

code1:

        FXMLLoader loader = new FXMLLoader();
        Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));
        Screen1Controller controller = loader.getController();
        if(controller == null)
            System.out.println(" controller is null");
            else System.out.println("controller is not null");

output:
controller is null

code2:

        FXMLLoader loader =  new FXMLLoader(getClass().getResource("Screen1.fxml"));
        Parent root = (Parent)loader.load();
//        FXMLLoader loader = new FXMLLoader();
//        Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));
        Screen1Controller controller = loader.getController();
        if(controller == null)
            System.out.println(" controller is null");
            else System.out.println("controller is not null");

output:
controller is not null

I thought that they will give the same result? Is it not?

Upvotes: 0

Views: 63

Answers (1)

Krzysztof Kosmatka
Krzysztof Kosmatka

Reputation: 487

In line

Parent root = (Parent) loader.load(getClass().getResource("Screen1.fxml"));

you call getResource(URL). That method is static, so it doesn't change any instance of FXMLLoader (and particulary doesn't create controller inside your loader).

Perhaps you wanted to call getResource(InputStream), which isn't static. If so, you should change your code to:

Parent root = (Parent) loader.load(getClass().getResourceAsStream("Screen1.fxml"));

Upvotes: 2

Related Questions