0

I've searched through the questions on here and none of the answers seem to fix my issue.

To simplify the problem: I have 2 scenes, my main pane and a statistics dialog.

When I select the name in my main pane it opens the statistics dialog. Unfortunately I can't get it to pass any information from the main pane to the statistics dialog. I check the information the line before I run the method controller.initData(Player player) and it shows an object with the correct information. But every time I run the app it crashes with a null pointer exception on the method call.

Here's the calling method to open the statistics dialog:

    @FXML
public void playerNameCLicked() {
    Player currentPlayer = gamer.getPlayer();
    Dialog<ButtonType> dialogPlayerStats = new Dialog<>();

    dialogPlayerStats.setTitle(currentPlayer.getName() + " statistics");

    FXMLLoader fxmlLoader = new FXMLLoader();
    fxmlLoader.setLocation(getClass().getResource("DialogPlayerStats.fxml"));

    ControllerPlayerStats controller = fxmlLoader.getController();
    controller.initData(currentPlayer);

    try{
        dialogPlayerStats.getDialogPane().setContent(fxmlLoader.load());
        System.out.println("Player statistics loaded");
    } catch(IOException e){
        System.out.println("Could not load player stats");
        e.printStackTrace();
    }

    dialogPlayerStats.getDialogPane().getButtonTypes().add(ButtonType.OK);
    Optional<ButtonType> result = dialogPlayerStats.showAndWait();

    if(result.isPresent()){ // && result.get() == ButtonType.OK
        dialogPlayerStats.close();
    }
}

and here is the statistics dialog controller:

public class ControllerPlayerStats{

/*Various variable assignments*/

public ControllerPlayerStats(){
    assignData();
}

void initData(Player player){
    this.player = player;
}

}

If I don't use the call controller.initData(Player player) then the dialog opens and looks as expected (albeit without and data). If I use it I get a null pointer.

I've tried to move the call to after the try block and have the same issue. I am new to java and fully expect the answer to be simple, but all the other answers I looked up either drown me or don't work.

Thanks in advance,

J

JimmyMac
  • 1
  • 3
  • 1
    The `FXMLLoader` doesn’t create the controller until you load the FXML (if you think about it, it’s not possible for it to do so, since the class used to instantiate the controller is specified in the FXML file). Consequently, `controller` is null. Just move the `getController()` and `initData()` calls for after you call `load()` – James_D Jul 11 '20 at 16:46
  • Excellent, thank you. So simple. Seems I have a new issue, it's not loading my statistics dialog. I'll see what I can do about that and hopefully won't need to come back :) Appreciate your help. J – JimmyMac Jul 11 '20 at 17:40

0 Answers0