Is there a way to style an independent TableView column?

后端 未结 1 1798
忘掉有多难
忘掉有多难 2021-01-29 05:29

I can use the CSS to style cells, but what if I want a different style (like using a different text color) for just one column.

Maybe I am missing something.

相关标签:
1条回答
  • 2021-01-29 06:25

    You should to use TableColumn#setCellFactory() to customize cell item rendering.
    For example, datamodel with like this 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..
    

    and the common getCustomCellFactory() method:

    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;
                }
            };
        }
    
    0 讨论(0)
提交回复
热议问题