首页 > 解决方案 > 覆盖 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);
    }
}

所以我想要的是,只有那一列不应该有样式

先感谢您!

标签: javafx

解决方案


这里的问题是-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>

推荐阅读