You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaFX 17:修改特定CheckBoxTreeCell实例的复选框样式

日志目录树的动态样式标识实现

需求背景

我用CheckBoxTreeView展示日志文件夹的目录树,允许用户选择哪些内容在TableView中显示。程序运行期间,日志文件/文件夹会被动态创建或更新,我已经监听了这些更新并同步展示给用户,但目前只能对CheckBoxTreeCell进行操作。我希望通过修改TreeCell复选框的边框和/或背景,来标识这些更新的条目。

实现思路

通过为CheckBoxTreeCell添加或移除样式类,结合CSS定义不同状态下的样式,以此区分日志条目更新状态。

Java实现代码

private void updateCell(CheckBoxTreeCell<LogFile> cell) {
    cell.getStyleClass().removeAll(Arrays.asList("logfile-created", "logfile-deleted", 
            "logfile-updated", "logfile-nochange"));
    LogFile logfile = cell.getItem();
    if (logfile != null) {
        LogStateEnum state = logfile.getState();
        // 更新样式类
        switch (state) {
        case CREATED:
            cell.getStyleClass().add("logfile-created");
            break;
        case DELETED:
            cell.getStyleClass().add("logfile-deleted");            
            break;
        case UPDATED:
            cell.getStyleClass().add("logfile-updated");
            Services.getLogService().debug(THIS_CLASS, MARKER, "styles - [" + Arrays.toString(cell.getStyleClass().toArray()) + "]");
            break;
        default:
            cell.getStyleClass().add("logfile-nochange");
            Services.getLogService().debug(THIS_CLASS, MARKER, logfile + " has styles - [" + Arrays.toString(cell.getStyleClass().toArray()) + "]");
        }
    }
}

对应的CSS样式

.root {
    -default-text-color: rgb(204,204,204);
    -default-text-entry-color: rgb(105,105,105);
    -default-window-color: rgb(0,0,0);

}
.tree-cell {
    -fx-background-color: -default-window-color;
    -fx-text-fill: -default-text-color;
}

.tree-cell:selected {
    -fx-background-color: -default-text-entry-color;
    -fx-text-fill: -default-window-color;
}

.tree-cell:filled:hover {
    -fx-background-color: -default-text-entry-color;
    -fx-text-fill: -default-window-color;
}

.logfile-updated {
    -fx-text-fill: green ;
}

.logfile-deleted {
    -fx-text-fill: red ;
}

.logfile-created {
    -fx-text-fill: yellow ;
}

.logfile-nochange {
    -fx-text-fill: -default-text-color;
}

内容的提问来源于stack exchange,提问作者dmsonice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 12:12:39