javafx - 覆盖 TableCell 上的 TableRow 样式
问题描述
所以我有以下问题。我有一个 JavaFX TableView,其中所有单元格都具有相同的样式,但只有一个。对于那个单元格,我想删除所有样式,但我猜 RowFactory 有一些优先级或其他什么。
我有一些这样的代码:
FXML
<TableView fx:id="tableView">
<columns>
<TableColumn fx:id="tcolNoStyle"/>
<TableColumn fx:id="tcolStyled"/>
</columns>
</TableView>
控制器
public class TableController {
@FXML
TableView<TableData> tableView;
@FXML
TableColumn<TableData, String> tcolNoStyle;
@FXML
TableColumn<TableData, String> tcolStyled;
@FXML
public void initialize(){
tableView.setRowFactory(row -> new RowFactory());
tcolNoStyle.setCellFactory(cell -> new CellFactoryForNoStyling());
}
}
表格背后的数据
public class TableData {
public final SimpleStringProperty noStyleTextProperty;
public final SimpleStringProperty styledTextProperty;
public TableData(){
noStyleTextProperty = new SimpleStringProperty();
styledTextProperty = new SimpleStringProperty();
}
}
行工厂
public class RowFactory extends TableRow<TableData> {
public RowFactory(){
itemProperty().addListener(((observable, oldValue, newValue) -> {
if (newValue != null){
setStyle("-fx-text-alignment: right");
}
}));
}
}
CellFactory 一个没有风格的 Cell
public class CellFactoryForNoStyling extends TableCell<TableData, String> {
public CellFactoryForNoStyling(){
super();
setStyle(null);
}
@Override
protected void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
setStyle(null);
}
}
所以我想要的是,只有那一列不应该有样式
先感谢您!
解决方案
这里的问题是-fx-text-alignment
属性是继承的。setStyle(null)
仅确保没有对其调用的节点进行其他更改。
可能最简单的选择是使用以下命令简单地指定默认值setStyle
:
public CellFactoryForNoStyling() {
setStyle("-fx-text-alignment: left");
}
不过,您可以将样式留给 CSS 样式表。这比使用内联样式方便得多,因为用这种方式处理选择、焦点等要容易得多。
例如,您可以将以下样式表添加到场景中;这样你就不要使用自定义cellValueFactory
/ rowFactory
:
/* default cell style */
.my-table .table-cell {
-fx-text-alignment: right;
}
/* overwrite above style using selector with higher specifity */
.my-table .table-cell.unstyled {
-fx-text-alignment: inherit;
}
<TableView fx:id="tableView" styleClass="my-table"> <!-- style class added here-->
<columns>
<TableColumn fx:id="tcolNoStyle" styleClass="unstyled"/> <!-- style class added here -->
<TableColumn fx:id="tcolStyled"/>
</columns>
</TableView>
推荐阅读
- c++ - 如何在 lambda 中捕获函数结果?
- django - 当数据库路由器上的 allow_migrate() 返回 false 时,django 会做什么?
- python - 谷歌 Colab 没有显示图
- javascript - 嵌套 for 循环的最佳替代方案是什么?
- php - 如何在 OpenCart 中备份后修复错误 500
- kubernetes - 通过 Kubernetes Dashboard 获取 helm 发布值(helm show values)
- typescript - 打字稿异步生成器编译/类型问题
- angular - 如何更改传入的@Input 值并发出@Output
- python - for 循环遍历具有多个时间步的 csv 文件
- python - RDD(array(list())) 映射到python中的字段及其值