【问题标题】:JavaFX Set Cell Background Color of TableColumnJavaFX设置TableColumn的单元格背景颜色
【发布时间】:2017-02-08 12:37:43
【问题描述】:
TableColumn tc = new TableColumn();

tc.getStyleClass.add(".style in css file")

我使用 CSS 文件设置 TableColumn,我想为每个单元格设置不同的背景颜色。我怎样才能做到这一点?

示例)TableColumn 1~5
TableColumn 1, row 3 有黑色和 TableColumn 5, row 4 有绿色...等

【问题讨论】:

  • 所以单元格颜色不同,而不是整行?
  • 那家伙不认为他在等我们为他编码。他之前的问题是如何更改行背景颜色。他只能在以前的答案中更改一行并轻松解决该问题。让他一个人做,别再创造新话题了

标签: javafx background tableview cell tablecell


【解决方案1】:

要更改TableView 中特定单元格的行为,您需要设置TableColumnscellFactory。这是一个例子:

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class TableMCVE extends Application {
    @Override
    public void start(Stage stage) {

        ObservableList<ObservableList<String>> tableData = FXCollections.observableArrayList();
        tableData.add(FXCollections.observableArrayList("Row1Col1", "Row1Col2"));
        tableData.add(FXCollections.observableArrayList("Row2Col1", "Row2Col2"));
        tableData.add(FXCollections.observableArrayList("Row3Col1", "Row3Col2"));

        TableView<ObservableList<String>> table = new TableView<ObservableList<String>>();

        TableColumn<ObservableList<String>, String> col1 = new TableColumn<ObservableList<String>, String>("Col1");
        col1.setCellValueFactory(e -> new SimpleStringProperty(e.getValue().get(0)));

        // Set the cell factory of the column with a custom TableCell to modify its behavior.
        col1.setCellFactory(e -> new TableCell<ObservableList<String>, String>() {
            @Override
            public void updateItem(String item, boolean empty) {
                // Always invoke super constructor.
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item);

                    // If index is two we set the background color explicitly.
                    if (getIndex() == 2) {
                        this.setStyle("-fx-background-color: green;");
                    }
                }
            }
        });

        TableColumn<ObservableList<String>, String> col2 = new TableColumn<ObservableList<String>, String>("Col2");
        col2.setCellValueFactory(e -> new SimpleStringProperty(e.getValue().get(1)));

        // Set the cell factory of the column with a custom TableCell to modify its behavior.
        col2.setCellFactory(e -> new TableCell<ObservableList<String>, String>() {
            @Override
            public void updateItem(String item, boolean empty) {
                // Always invoke super constructor.
                super.updateItem(item, empty);

                if (item == null || empty) {
                    setText(null);
                } else {
                    setText(item);

                    // If index is zero we set the background color explicitly.
                    if (getIndex() == 0) {
                        this.setStyle("-fx-background-color: blue;");
                    }
                }
            }
        });

        table.getColumns().addAll(col1, col2);
        table.getItems().addAll(tableData);

        stage.setScene(new Scene(table));
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}

在我的示例中,我只是根据单元格的索引设置颜色,但您可以将其更改为更有意义的内容。例如。颜色可以基于单元格的值。

【讨论】:

    【解决方案2】:

    创建一个cellFactory,它根据列和行索引选择背景颜色。

    例子:

    TableView<Item<String>> tableView = new TableView<>();
    // sample item class contains a single property with the same type as the type parameter (String in this case)
    tableView.getItems().addAll(
            new Item<>("1"),
            new Item<>("2"),
            new Item<>("4"),
            new Item<>("5"),
            new Item<>("6"),
            new Item<>("7"),
            new Item<>("8"),
            new Item<>("9")
    );
    
    // create columns
    TableColumn<Item<String>, String> column1 = new TableColumn<>("value");
    TableColumn<Item<String>, Void> column2 = new TableColumn<>();
    tableView.getColumns().addAll(column1, column2);
    
    // create list of colors (CSS)
    final List<String> colors = Arrays.asList(
            "blue",
            "green",
            "red",
            "violet",
            "yellow",
            ...
    );
    
    Callback factory = new Callback<TableColumn<Item<String>, Object>, TableCell<Item<String>, Object>>() {
    
        private int columns = tableView.getColumns().size();
    
        @Override
        public TableCell<Item<String>, Object> call(TableColumn<Item<String>, Object> param) {
            return new TableCell<Item<String>, Object>() {
    
                private int columnIndex = param.getTableView().getColumns().indexOf(param);
    
                @Override
                public void updateIndex(int i) {
                    super.updateIndex(i);
                    // select color based on index of row/column
                    if (i >= 0) {
                        // select color repeating the color, if we run out of colors
                        String color = colors.get((i * columns + columnIndex) % colors.size());
                        this.setStyle("-fx-my-cell-background: " + color + ";");
                        System.out.println(getStyle());
                    }
                }
    
                @Override
                protected void updateItem(Object item, boolean empty) {
                    super.updateItem(item, empty);
    
                    // assign item's toString value as text
                    if (empty || item == null) {
                        setText(null);
                    } else {
                        setText(item.toString());
                    }
                }
    
            };
        }
    
    };
    
    column1.setCellValueFactory(new PropertyValueFactory<>("value"));
    column1.setCellFactory(factory);
    column2.setCellFactory(factory);
    
    Scene scene = new Scene(tableView);
    scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
    

    此处描述了有效的 CSS 颜色字符串:https://docs.oracle.com/javase/8/javafx/api/javafx/scene/doc-files/cssref.html#typecolor

    style.css

    .table-cell:filled {
        -fx-background-color: -fx-my-cell-background;
    }
    
    .table-view:row-selection .table-row-cell:selected .table-cell {
        -fx-background-color: null;
    }
    
    .table-view:cell-selection .table-cell:selected {
        -fx-background-color: -fx-table-cell-border-color, -fx-background;
    }
    

    【讨论】:

    • WARNING: Caught 'java.lang.ClassCastException: class java.lang.String cannot be cast to class javafx.scene.paint.Paint (java.lang.String is in module java.base of loader 'bootstrap'; javafx.scene.paint.Paint 在加载器'app')' 的模块 javafx.graphics 中,同时从样式表文件中的规则'*.table-cell:filled' 转换'-fx-background-color' 的值:/.../style.css
    猜你喜欢
    • 1970-01-01
    • 2010-11-21
    • 2017-04-30
    • 1970-01-01
    • 2016-12-18
    • 1970-01-01
    • 2015-06-02
    • 2012-06-06
    • 2019-10-21
    相关资源
    最近更新 更多