java - :selected pseudoclass style not applied to cell

标签 java css javafx css-selectors

我在场景中有一些 TableView,我想在其中突出显示所选的单元格。根据JavaFX CSS reference , Cells 上有一个伪类 :selected ,所以我尝试了以下 css:

.cell:selected {
    -fx-effect: dropshadow(gaussian, 10, .2, 4, 4);
}

但是样式没有应用到单元格。当我使用 .cell:hover 时,它按预期工作。

以下是简化的 FXML:

<Pane fx:controller="Controller">
   <children>
        <TableView fx:id="table" />
   </children>
</Pane>

我用它作为 Controller :

public class Controller implements Initializable{
    @FXML
    private TableView<SomeClass> table;
    // some other things

    @Override
    public void initialize(URL url, ResourceBundle bundle) {
        Objects.requireNonNull(table, "Table was not injected");
        // create columns, initialize other stuff
        table.getColumns().clear();
        table.getColumns().addAll(/*some columns */);
        table.setEditable(false);
        table.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        table.setColumnResizePolicy(TableView.CONSTRAINED_RESIZE_POLICY);
    }
}

为什么 CSS 没有应用到选定的单元格?

最佳答案

这里的问题是 JavaFX 处理单元格和行选择的方式。

让我们引用TableViewSelectionModel的javadoc片刻,尤其是 cellSelectionEnabled 属性:

A boolean property used to represent whether the table is in row or cell selection modes. By default a table is in row selection mode which means that individual cells can not be selected. Setting cellSelectionEnabled to be true results in cells being able to be selected (but not rows).

我们可以得出结论,您的单元格未标记为选中,因为您处于行选择模式。
您可以通过调整您的 css 选择器以依赖行来解决这个问题(类似这样):

.table-row-cell:selected .cell {
    -fx-effect: ...;
}

您可以结合 TableView 上的 :cell-selection:row-selection 使其更有用:

.table-view:row-selection .table-row-cell:selected .cell, .table-view:cell-selection .cell:selected {
    -fx-effect: ...;
}

将应用于选定的单元格,无论您的 TableViewSelectionModel

的操作方式如何

关于java - :selected pseudoclass style not applied to cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36676441/

相关文章:

java - 如何在 TableView (JAVAFX) 中选择/突出显示下一行

css - 如何设置 repeat-x 和滚动背景图像的长度和位置?

html - 简单的 css 悬停问题

JavaFX 具有不同父对象的对象之间的冲突检测

添加列表项时 JavaFX TableView 行不刷新

java - 除非 javaFX 中两个事件为真,否则如何将按钮设置为保持禁用状态?

java - 通过 Java 中的首选项访问 HKEY_CURRENT_USER

java - 扫描仪与 InputStreamReader

java - 如何在带有变量的 PreparedStatement 中使用 SQL 通配符

javascript - 样式滚动条在 chrome 和 safari 上工作完美,但在 mozilla 上不工作