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

如何用CSS为选中但未获焦点的JavaFX表格行设置背景色

问题:JavaFX表格选中行的焦点样式设置

我编写了如下JavaFX代码:

public class JavaFxTest7 extends Application {

    private static class Student {

        private int id;

        private int mark;

        public Student(int id, int mark) {
            this.id = id;
            this.mark = mark;
        }

        public int getId() {
            return id;
        }

        public int getMark() {
            return mark;
        }
    }

    private TableView<Student> table = new TableView<>(FXCollections.observableList(
            List.of(new Student(1, 3), new Student(2, 4), new Student(3, 5))));

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

    @Override
    public void start(Stage primaryStage) {
        var idColumn = new TableColumn<Student, Integer>();
        idColumn.setCellValueFactory((data) ->  new ReadOnlyObjectWrapper<>(data.getValue().getId()));
        var markColumn = new TableColumn<Student, Integer>();
        markColumn.setCellValueFactory((data) ->  new ReadOnlyObjectWrapper<>(data.getValue().getMark()));
        table.getColumns().addAll(idColumn, markColumn);

        VBox root = new VBox(new TextField(), table);
        var scene = new Scene(root, 400, 300);
        var css= this.getClass().getResource("test7.css").toExternalForm();

        scene.getStylesheets().addAll(css);
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

需求是:为选中但未获焦点的表格行设置黄色背景,为获焦点的选中行设置绿色背景。

我尝试了以下CSS代码:

.table-row-cell:selected:focused {
    -fx-background-color: green;
    -fx-background-insets: 0;
}

.table-row-cell:selected {
    -fx-background-color: yellow;
    -fx-background-insets: 0;
}

但设置后,选中行的样式未按预期生效,无法正确区分焦点状态。

又尝试了这段代码:

.table-row-cell:focused {
    -fx-background-color: green;
    -fx-background-insets: 0;
}

.table-row-cell:selected {
    -fx-background-color: yellow;
    -fx-background-insets: 0;
}

结果是所有获得焦点的行(无论是否选中)都显示绿色,不符合需求。

请问该如何实现需求?


解决方案

使用以下CSS代码即可实现需求:

/* 选中但表格未获得焦点时的行样式 */
.table-row-cell:selected {
    -fx-background-color: yellow;
    -fx-background-insets: 0;
}

/* 表格获得焦点时的选中行样式 */
.table-view:focused .table-row-cell:selected {
    -fx-background-color: green;
    -fx-background-insets: 0;
}

说明:

JavaFX中,表格的焦点状态是作用在TableView容器上,而非单独的行。之前的问题在于选择器优先级和状态匹配错误:

  • 当表格未获得焦点时,直接匹配.table-row-cell:selected即可设置黄色背景;
  • 当表格获得焦点时,需要通过.table-view:focused来限定选中行的样式,提高选择器优先级,覆盖默认样式,从而显示绿色背景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 17:42:43