2017-05-23 83 views
2

我有一个TreeTableView<MyCustomRow>,我想动态添加列。在MyCustomRow我有一个Map<Integer, SimpleBooleanProperty>与行中的值。我以这种方式添加新列:JavaFx动态列值

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; 
} 

然后table.getColumns().add(newColumn())

问题是,当我连续检查一个CheckBox时,该行中的所有复选框都被检查。这里是我行的代码:

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

} 

所以我设置取决于colNr单元格的值,我也试着调试和似乎值在values地图不同,所以我不知道为什么所有的复选框都选中时只检查一个。

回答

2

在这一行,

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

中示出了细胞时,处理程序被调用。因此,所有colNr都是最新的值,最后一个索引的布尔属性与所有单元格相关联。

要拨打与在newColumn()时的值调用处理程序,例如:

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

非常感谢你,它工作得很好:) – Sunflame