Javafx Tree Table视图:如何给根节点的直接子节点分配序号
Javafx Tree Table view: how to assign serial number to the direct child nodes of the root node
我正在尝试以串行方式对根节点的直接子节点进行编号(child-1,child-2 ...)。
这是我为 myColumn 设置单元格值工厂的方法:
private void setCellValueFactory() {
myColumn.setPrefWidth(120);
final int[] si_SubsetCount = {
1
};
myColumn.setCellValueFactory(
(TreeTableColumn.CellDataFeatures < MyDataClass, String > p) - > {
TreeItem < JVCC_PageHeaderInfo > ti_Row = p.getValue();
MyDataClass myDataClass = p.getValue().getValue();
String text;
if (ti_Row.isLeaf()) {
//leaf
} else if (ti_Row.getParent() != null) {
text = "Child-" + si_SubsetCount[0];
si_SubsetCount[0]++;
} else {
si_SubsetCount[0] = 1;
text = "Root";
}
return new ReadOnlyObjectWrapper < > (text);
});
}
但我的输出如下:
>Root
>child-4
>leaf
>leaf
>child-8
>leaf
>leaf
我不明白为什么编号是 4、8... 而不是 1、2...
谁能帮我解决这个问题。
那是因为您无法控制何时调用用于计算每行值的 CellValueFactorys 方法。它可能会为一行调用多次,这就是为什么您的计数器没有为每一行显示正确的值。
这里首选动态方法。如果您只需要在 3 个节点级别之间进行区分,例如 root/child/leaf,那么您可以这样做:
myColumn.setCellValueFactory( ( final CellDataFeatures<String, String> p ) ->
{
final TreeItem<String> value = p.getValue();
String text = "";
if ( value.isLeaf() )
text = "leaf";
else if ( value.getParent() != null )
text = "Child-" + (value.getParent().getChildren().indexOf( value ) + 1);
else
text = "root";
return new ReadOnlyStringWrapper( text );
} );
由于 TreeItem 的子项存储在 ObservableList 中,您只需询问它们的索引并加 1,因为索引从零开始。
我正在尝试以串行方式对根节点的直接子节点进行编号(child-1,child-2 ...)。
这是我为 myColumn 设置单元格值工厂的方法:
private void setCellValueFactory() {
myColumn.setPrefWidth(120);
final int[] si_SubsetCount = {
1
};
myColumn.setCellValueFactory(
(TreeTableColumn.CellDataFeatures < MyDataClass, String > p) - > {
TreeItem < JVCC_PageHeaderInfo > ti_Row = p.getValue();
MyDataClass myDataClass = p.getValue().getValue();
String text;
if (ti_Row.isLeaf()) {
//leaf
} else if (ti_Row.getParent() != null) {
text = "Child-" + si_SubsetCount[0];
si_SubsetCount[0]++;
} else {
si_SubsetCount[0] = 1;
text = "Root";
}
return new ReadOnlyObjectWrapper < > (text);
});
}
但我的输出如下:
>Root
>child-4
>leaf
>leaf
>child-8
>leaf
>leaf
我不明白为什么编号是 4、8... 而不是 1、2...
谁能帮我解决这个问题。
那是因为您无法控制何时调用用于计算每行值的 CellValueFactorys 方法。它可能会为一行调用多次,这就是为什么您的计数器没有为每一行显示正确的值。
这里首选动态方法。如果您只需要在 3 个节点级别之间进行区分,例如 root/child/leaf,那么您可以这样做:
myColumn.setCellValueFactory( ( final CellDataFeatures<String, String> p ) ->
{
final TreeItem<String> value = p.getValue();
String text = "";
if ( value.isLeaf() )
text = "leaf";
else if ( value.getParent() != null )
text = "Child-" + (value.getParent().getChildren().indexOf( value ) + 1);
else
text = "root";
return new ReadOnlyStringWrapper( text );
} );
由于 TreeItem 的子项存储在 ObservableList 中,您只需询问它们的索引并加 1,因为索引从零开始。