我有一个有几个孩子的节点,并希望保留折叠/展开箭头,这是该节点的默认图标,但我想要另一个图形,我想放在箭头旁边。 JavaFX树视图是否允许这样做?
答案 0 :(得分:0)
将图形传递给TreeItem
:
TreeItem<String> root = new TreeItem<>("Root", new Rectangle(16, 16, Color.CORAL));
等
或使用细胞工厂:
TreeView<String> tree = new TreeView<>();
tree.setCellFactory(tv -> new TreeCell<String>() {
private final Node graphic = new Rectangle(16, 16, Color.CORAL);
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : graphic);
setText(empty ? null : item);
}
});
请注意,对于大型树,第二种技术可能更有效,因为它只为每个单元创建图形(在本例中为两个节点),而第一种技术创建图形对于树中的每个项(无论是否显示)。可以说(我强烈反对),第二种技术可以更好地分离关注点(在第一种解决方案中,图形是数据的一部分,这是完全错误的。)
第一项技术的SSCCE:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class TreeGraphicTest extends Application {
@Override
public void start(Stage primaryStage) {
TreeItem<String> root = new TreeItem<>("Root", new Rectangle(16, 16, Color.CORAL));
for (int i = 1 ; i <= 3 ; i++) {
root.getChildren().add(new TreeItem<>("Child "+i, new Rectangle(16, 16, Color.CORNFLOWERBLUE)));
}
TreeView<String> tree = new TreeView<>(root);
primaryStage.setScene(new Scene(tree));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
SSCCE第二种技术:
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
public class TreeGraphicTest extends Application {
@Override
public void start(Stage primaryStage) {
TreeItem<String> root = new TreeItem<>("Root");
for (int i = 1 ; i <= 3 ; i++) {
root.getChildren().add(new TreeItem<>("Child "+i));
}
TreeView<String> tree = new TreeView<>(root);
tree.setCellFactory(tv -> new TreeCell<String>() {
private final Node rootGraphic = new Rectangle(16, 16, Color.CORAL) ;
private final Node childGraphic = new Rectangle(16, 16, Color.CORNFLOWERBLUE) ;
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setGraphic(empty ? null : getTreeItem() == root ? rootGraphic : childGraphic);
setText(empty ? null : item);
}
});
primaryStage.setScene(new Scene(tree));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
屏幕截图(适用于):