gpt4 book ai didi

JavaFx。按条件更改 TreeItem 样式

转载 作者:行者123 更新时间:2023-11-28 16:02:28 31 4
gpt4 key购买 nike

有TreeView,每个元素都实现了Viewable接口(interface):

public interface Viewable {

enum ViewStyle {

NEW("-fx-background-color: b8faa7;"),
NEW_PARENT("-fx-background-color: b8ebbb;"),
LOCKED("-fx-background-color: adadad; "),
HAS_NO_DATA("-fx-background-color: eb8d8d;");

String style;

ViewStyle(String style){
this.style = style;
}

public String getStyle() {
return style;
}

}

ViewStyle getViewStyle();
void setViewStyle(ViewStyle style);
StringProperty styleProperty();

String getTreeItemTitle();
void setTreeItemTitle(String title);
StringProperty titleProperty();

}

每个元素都有自己的.styleProperty(),并从ViewStyle.getStyle()获取值

此属性为每个 TreeCell.styleProperty() 绑定(bind):

treeView.setCellFactory(new Callback<TreeView<Viewable>, TreeCell<Viewable>>() {
@Override
public TreeCell<Viewable> call(TreeView<Viewable> param) {
return new TreeCell<Viewable>() {
@Override
protected void updateItem(Viewable item, boolean empty) {
textProperty().unbind();
styleProperty().unbind();
if (empty || item == null) {
setGraphic(null);
textProperty().set(null);
styleProperty().set(null);
return;
}
if (item != null) {
styleProperty().bind(item.styleProperty());
textProperty().bind(item.titleProperty());
}
super.updateItem(item, empty);
}
};
}
});

问题是树单元格在选择中显示得很丑。即所选单元格的颜色不会改变。只改变字母的颜色(根据默认主题),但不是很方便。因此,可能需要附加 .css 文件。同时,我不明白如何根据当前的 ViewStyle 更改单元格的样式(默认和选中时)。

最佳答案

您可以简单地将 css 属性更改为仅用于未选定单元格的属性 (-fx-control-inner-background):

enum ViewStyle {

NEW("-fx-control-inner-background: b8faa7;"),
NEW_PARENT("-fx-control-inner-background: b8ebbb;"),
LOCKED("-fx-control-inner-background: adadad; "),
HAS_NO_DATA("-fx-control-inner-background: eb8d8d;");

另请注意,您在 updateItem 方法的覆盖版本中做了一些不应该做的事情:不总是调用 super.updateItem。这可能导致 filled/empty 伪类未正确分配,并且 TreeCellitem 属性不包含来自最近的 updateItem 调用的元素。你应该做这样的事情:

@Override
protected void updateItem(Viewable item, boolean empty) {
textProperty().unbind();
styleProperty().unbind();
if (empty || item == null) {
setText(null);
setStyle(null);
} else {
styleProperty().bind(item.styleProperty());
textProperty().bind(item.titleProperty());
}
super.updateItem(item, empty);
}

关于JavaFx。按条件更改 TreeItem 样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39851003/

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