2016-04-17 63 views
3

我在场景中有一些TableView,我想突出显示选定的单元格。按照JavaFX CSS reference,对细胞伪类: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> 

我用这个作为控制器:

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中不能应用到所选单元格?

回答

6

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

让我们请教TableViewSelectionModel的Javadoc了一会儿,尤其是cellSelectionEnabled属性:

用于表示该表是否为行或单元选择模式的布尔属性。默认情况下,表格处于行选择模式,这意味着不能选择单个单元格。将cellSelectionEnabled设置为true会导致单元格被选中(但不是行)。

我们可以得出结论,您的单元格未被标记为选中状态,因为您处于行选模式。
您可以解决此通过调整你的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