【问题标题】:Is there a way to style an independent TableView column?有没有办法为独立的 TableView 列设置样式?
【发布时间】:2012-05-28 12:24:07
【问题描述】:

我可以使用 CSS 来设置单元格的样式,但是如果我只想为一列设置不同的样式(例如使用不同的文本颜色)怎么办。

也许我错过了什么。

【问题讨论】:

    标签: css tableview javafx


    【解决方案1】:

    您应该使用TableColumn#setCellFactory() 自定义单元格项目渲染。
    例如,像这样的数据模型Person class:

    // init code vs..
    TableColumn firstNameCol = new TableColumn("First Name");
    firstNameCol.setMinWidth(100);
    firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
    firstNameCol.setCellFactory(getCustomCellFactory("green"));
    
    TableColumn lastNameCol = new TableColumn("Last Name");
    lastNameCol.setMinWidth(100);
    lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
    lastNameCol.setCellFactory(getCustomCellFactory("red"));
    
    table.setItems(data);
    table.getColumns().addAll(firstNameCol, lastNameCol);
    
    // scene create code vs..
    

    以及常见的getCustomCellFactory()方法:

    private Callback<TableColumn<Person, String>, TableCell<Person, String>> getCustomCellFactory(final String color) {
            return new Callback<TableColumn<Person, String>, TableCell<Person, String>>() {
    
                @Override
                public TableCell<Person, String> call(TableColumn<Person, String> param) {
                    TableCell<Person, String> cell = new TableCell<Person, String>() {
    
                        @Override
                        public void updateItem(final String item, boolean empty) {
                            if (item != null) {
                                setText(item);
                                setStyle("-fx-text-fill: " + color + ";");
                            }
                        }
                    };
                    return cell;
                }
            };
        }
    

    【讨论】:

    • 不过,一个简单的基于 CSS 的解决方案会很棒,只需向 TableColumn 对象添加一个 ID 字段,您可以使用它来设置它的样式
    猜你喜欢
    • 1970-01-01
    • 2016-02-12
    • 1970-01-01
    • 2011-02-28
    • 2021-05-18
    • 1970-01-01
    • 2022-06-29
    • 2015-03-07
    • 1970-01-01
    相关资源
    最近更新 更多