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

如何在JavaFX中不使用CSS修改TableView行的文本颜色

在JavaFX代码中直接修改TableView选中行的文本颜色

你当前的代码仅修改了TableRow的背景色,但-fx-text-fill样式是作用于TableCell而非TableRow的,因此直接给TableRow设置该样式不会生效。要在代码中实现选中行文本变色,需要遍历行内的所有TableCell并单独设置样式:

tableSoldCoffees.setRowFactory(typesOfCoffeesTableView -> new TableRow<TypesOfCoffees>() {
    @Override
    protected void updateItem(TypesOfCoffees item, boolean empty) {
        super.updateItem(item, empty);
        if (isSelected()) {
            // 设置选中行背景色
            setStyle("-fx-background-color: #74512D");
            // 遍历行内所有TableCell,设置文本颜色
            this.getChildren().forEach(node -> {
                if (node instanceof TableCell) {
                    ((TableCell<?, ?>) node).setStyle("-fx-text-fill: white;");
                }
            });
        } else {
            // 取消选中时重置背景色
            setStyle("");
            // 重置所有TableCell的文本样式
            this.getChildren().forEach(node -> {
                if (node instanceof TableCell) {
                    ((TableCell<?, ?>) node).setStyle("");
                }
            });
        }
    }
});

这段代码的逻辑和你提到的CSS选择器.myTable .table-row-cell:selected .table-cell完全一致:选中行时,先给TableRow设置背景色,再遍历其下的所有TableCell设置文本颜色;取消选中时,重置所有样式恢复默认状态。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:44:55