【问题标题】:Override TableRow styling on TableCell覆盖 TableCell 上的 TableRow 样式
【发布时间】:2019-10-08 01:31:05
【问题描述】:

所以我有以下问题。 我有一个 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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2021-07-20
      • 2018-07-26
      • 1970-01-01
      • 2013-10-18
      • 2020-12-20
      • 2020-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      相关资源
      最近更新 更多