JavaFX: how do you target procedurally added rows in a VBox?

83 views Asked by At

So, I want to start manipulating elements in a VBox. I'm adding them procedurally with a for loop that loads in fxml rows.

public void scoreRows() {
    AtomicInteger rows = new AtomicInteger(1);
    for (int i = 0; i <= 10; i++) {
        if (rows.get() <=10) {
            HBox scoreCellRow = null;
            try {
                scoreCellRow = FXMLLoader.load(getClass().getResource("/views/score_cell.fxml"));
                rowHolder.getChildren().add(scoreCellRow);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("No more rows");
        }
    }
}

As I understand it, each time a row is added a new controller is instantiated. So I'm wondering how do I find these elements to target them. For example, what if I wanted to change the background color of every other row by changing the HBox fx:id cellHolder? Or what if I wanted to change the text in the first box of each row to be sequential Label fx:id roundNum?

Score sheet example

1

There are 1 answers

0
horribly_n00bie On BEST ANSWER

It turns out there are only 3 things you really need for this.

  1. A place to put the object

  2. A FXMLLoader and to get the directory

  3. The object and it's controller together

    //This is the place to put the object HBox scoreCellRow = null;

            try {
                //This is the FXMLLoader pointing to the directory
                FXMLLoader loader = new FXMLLoader(getClass().getResource("/views/score_cell.fxml"));
    
                //Now we can use the Loader that I named "loader" to load the fxml and get the controller
                scoreCellRow = loader.load();
                rowHolder.getChildren().add(scoreCellRow);
                ScoreCellCtrl scoreCellCtrl = loader.getController();
    
                //Once it's set up changing things as they are added is easy
                scoreCellCtrl.setRoundNum(String.valueOf(adjustedRnd));
                if (adjustedRnd % 2 == 0) {
                    scoreCellCtrl.getCellHolder().setStyle("-fx-background-color:#ffe89e;");
    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    

**the adjustedRnd is an int that I used with a for loop to label the rows correctly, adjusting for anything I wanted to insert between the rounds.