why these two codes give different outputs

76 Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

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"));