JavaFX 树视图TreeView
- 1、TreeView基础查看
- 2、显示案例
1、TreeView基础查看
javafx.scene.control.TreeView<T>
javafx.scene.control.TreeItem<T>
w3cschool:JavaFX 树视图
DOC-03-14 树视图(Tree View)
JavaFX视频教程第101课,TreeView的基本使用
JavaFX视频教程第102课,TreeView,TreeItem的几种事件
JavaFX视频教程第103课,TreeView,四种内置TreeCell效果
JavaFX视频教程第104课,TreeView,自定义TreeCell
JavaFX视频教程第105课,TreeView实现节点拖拽效果
2、显示案例
@FXML
protected void onButtonClick() {
hBoxArea.getChildren().clear();
File file = JavaFXTool.openFolderChooser(mStage);
if (file != null && file.isDirectory()) {
TreeItem<File> root = createNode(file);
treeView.setRoot(root);
// root.addEventHandler(TreeItem.<File>branchExpandedEvent(), event -> {
// XLog.d("分支展开事件" + event.getTreeItem().getValue().getPath());
// });
//
// root.addEventHandler(TreeItem.<File>branchCollapsedEvent(), event -> {
// XLog.d("分支折叠事件" + event.getTreeItem().getValue().getPath());
// });
//
// root.addEventHandler(TreeItem.<File>treeNotificationEvent(), event -> {
// XLog.d("所有通知事件: EventType=" + event.getEventType() + "; value=" + event.getTreeItem().getValue().getPath());
// });
treeView.setCellFactory((Callback<TreeView, TreeCell>) param -> {
TreeCell<File> treeCell = new TreeCell<File>() {
@Override
protected void updateItem(File item, boolean empty) {
super.updateItem(item, empty);
if (!empty) {
this.setText(item.getName());
if (item.isFile()) {
this.setOnMouseClicked(event -> {
if ("md".equals(Util.getExtension(item))) {
XLog.d("setOnMouseClicked: item.getPath()=" + item.getPath());
final String fileText = Util.getFileText(item);
final String text = MdParser.render(MdParser.parse(fileText));
XLog.d("setOnMouseClicked: MdParser =" + text);
Platform.runLater(() -> {
mWebEngine.loadContent(text);
});
}
});
}
} else {
this.setGraphic(null);
this.setText(null);
}
}
};
return treeCell;
});
hBoxArea.getChildren().add(treeView);
}
hBoxArea.getChildren().add(webView);
}
private TreeItem<File> createNode(final File f) {
return new TreeItem<File>(f) {
private boolean isLeaf;
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
@Override
public ObservableList<TreeItem<File>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
super.getChildren().setAll(buildChildren(this));
}
return super.getChildren();
}
@Override
public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
File f = (File) getValue();
isLeaf = f.isFile();
}
return isLeaf;
}
private ObservableList<TreeItem<File>> buildChildren(
TreeItem<File> TreeItem) {
File f = TreeItem.getValue();
if (f == null) {
return FXCollections.emptyObservableList();
}
if (f.isFile()) {
return FXCollections.emptyObservableList();
}
File[] files = f.listFiles();
if (files != null) {
ObservableList<TreeItem<File>> children = FXCollections.observableArrayList();
for (File childFile : files) {
children.add(createNode(childFile));
}
return children;
}
return FXCollections.emptyObservableList();
}
};
}