gpt4 book ai didi

java - 如何在 javafx TreeView 中使某些节点变为粗体?

转载 作者:行者123 更新时间:2023-12-02 04:45:30 27 4
gpt4 key购买 nike

如何在 javax TreeView 中显示带有粗体子项的节点名称? (离开节点应显示为非粗体)

最佳答案

在树上使用单元工厂,根据显示的树项是否为叶子,在它创建的树单元上设置 CSS 伪类的状态。然后,您可以使用外部 css 文件以您喜欢的任何方式设置叶节点和非叶节点的样式。

示例:

import javafx.application.Application;
import javafx.css.PseudoClass;
import javafx.scene.Scene;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class BoldNonLeafNodes extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
final BorderPane uiRoot = new BorderPane();

TreeItem<Integer> root = createTreeItem(1);

final TreeView<Integer> tree = new TreeView<>(root);

PseudoClass leaf = PseudoClass.getPseudoClass("leaf");
tree.setCellFactory(tv -> {
TreeCell<Integer> cell = new TreeCell<>();
cell.itemProperty().addListener((obs, oldValue, newValue) -> {
if (newValue == null) {
cell.setText("");
} else {
cell.setText(newValue.toString());
}
});
cell.treeItemProperty().addListener((obs, oldTreeItem, newTreeItem) ->
cell.pseudoClassStateChanged(leaf, newTreeItem != null && newTreeItem.isLeaf()));
return cell ;
});

uiRoot.setCenter(tree);

final Scene scene = new Scene(uiRoot);
scene.getStylesheets().add("bold-non-leaf-nodes.css");

primaryStage.setScene(scene);
primaryStage.setTitle(getClass().getSimpleName());
primaryStage.show();
}

private TreeItem<Integer> createTreeItem(int value) {
TreeItem<Integer> item = new TreeItem<>(value);
if (value < 10000) {
for (int i=0; i<10; i++) {
item.getChildren().add(createTreeItem(10*value+i));
}
}
return item ;
}

public static void main(String[] args) {
launch(args);
}
}

粗体非叶节点.css:

.tree-cell {
-fx-font-weight: bold ;
}
.tree-cell:leaf {
-fx-font-weight: normal ;
}

关于java - 如何在 javafx TreeView 中使某些节点变为粗体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29702725/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com