我在场景中有一些 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/