Sunflame
Sunflame

Reputation: 3186

JavaFx dynamic column values

I have a TreeTableView<MyCustomRow> and I want to add columns dynamically. In MyCustomRow i have a Map<Integer, SimpleBooleanProperty> with the values in the row. I'm adding the new column this way:

private TreeTableColumn<MyCustomRow, Boolean> newColumn() {
    TreeTableColumn<MyCustomRow, Boolean> column = new TreeTableColumn<>();
    column.setId(String.valueOf(colNr));
    column.setPrefWidth(150);
    column.setCellValueFactory(data -> data.getValue().getValue().getValue(colNr));
    column.setCellFactory(factory -> new CheckBoxTreeTableCell());
    column.setEditable(true);
    colNr++;
    return column; 
}

Then table.getColumns().add(newColumn()).

The problem is when I check a CheckBox in a row, all CheckBoxes in that row become checked. Here is the code for my row:

public class MyCustomRow {
    private Map<Integer, SimpleBooleanProperty> values = new HashMap<>();

    public MyCustomRow(Map<Integer, Boolean> values) {
        values.entrySet().forEach(entry -> this.values
                .put(entry.getKey(), new SimpleBooleanProperty(entry.getValue())));
    }

    public SimpleBooleanProperty getValue(Integer colNr) {
        if (!values.containsKey(colNr)) {
            values.put(colNr, new SimpleBooleanProperty(false));
        }
        return values.get(colNr);
    }

}

So I set the value of the cell depending on the colNr, i also tried to debug and it seems the values are different in the values map, so I have no idea why all the checkBoxes are checked when I check just one.

Upvotes: 2

Views: 656

Answers (1)

monolith52
monolith52

Reputation: 884

In this line,

column.setCellValueFactory(data -> data.getValue().getValue().getValue(colNr));

The handler is called when the cells are shown. Hence all of colNr are the newest value, the boolean property of the last index is associated with all cells.

To call the handler with the value at the time of newColumn() is called, for example:

final Integer colNrFixed = colNr;
column.setCellValueFactory(data -> data.getValue().getValue().getValue(colNrFixed));
// ...
colNr++;

Upvotes: 2

Related Questions