Search code examples
for-loopjavafxlookup

JavaFX iteration with .lookup


I am trying to make a minigame on JavaFX but I am encountering an issue where it says "currentPlayerBox" is null; it is meant to be a variable in a for loop that goes through the player areas' components to make sure they are reset for each player (1-4); here is the code:

for (int i=1; i < 5; i++){
            Pane currentPlayerBox = (Pane) root.lookup("player" + i + "Box");
            TextArea playerTextArea = (TextArea) currentPlayerBox.lookup("player" + i + "TextArea");
            ImageView playerImgWin = (ImageView) currentPlayerBox.lookup("player" + i + "WinImg");
            ImageView playerImgLose = (ImageView) currentPlayerBox.lookup("player" + i + "LoseImg");
            playerTextArea.clear();
            playerImgWin.setOpacity(0);
            playerImgLose.setOpacity(0);
            currentPlayerBox.getChildren().forEach (button -> button.setDisable(true));
            currentPlayerBox.setVisible(false);
           }

This does work if I use the actual fx:id manually; like player1Box, player2Box; but it returns null if I use Pane currentPlayerBox = (Pane) root.lookup("player" + i + "Box"); am I using this method wrong? Can I even do this or do I have to go 1 by 1 manually? I can post the FXML code if it is needed; but I am basically just trying to lookup some Panes inside an AnchorPane with no other parent in between. And yes, the fx:id of the AnchorPane is just "root" triplechecked that.


Solution

  • If you are setting an id, then you need to lookup by prepending the # to your string. On the other hand if you are looking for a style class then you need to prepend with .

    So I believe try changing the code to below and check :

    for (int i=1; i < 5; i++){
                Pane currentPlayerBox = (Pane) root.lookup("#player" + i + "Box");
                TextArea playerTextArea = (TextArea) currentPlayerBox.lookup("#player" + i + "TextArea");
                ImageView playerImgWin = (ImageView) currentPlayerBox.lookup("#player" + i + "WinImg");
                ImageView playerImgLose = (ImageView) currentPlayerBox.lookup("#player" + i + "LoseImg");
                playerTextArea.clear();
                playerImgWin.setOpacity(0);
                playerImgLose.setOpacity(0);
                currentPlayerBox.getChildren().forEach (button -> button.setDisable(true));
                currentPlayerBox.setVisible(false);
               }
    

    Out of topic, please also have a look at this to have a quick overview of id(s) and see if you are using it correctly.