找到你要的答案

Q:JavaFX TableView category/separation row

Q:JavaFX TableView类/分离排

I am having troubles figuring out how to approach this:

I'd like to have a TableView in my scene graph that will represent a certain class (Product). The class has a String type field that I would like to use to categorize the products. Therefore, I would like to populate the TableView in a loop, adding all the products , while adding a 'Category' row before each specific type of product.

So If I have for example 10 products and let's say 6 of them are of type 'Alcohol' and the rest of type 'Food' , the first row of the TableView would have it's 'name' column set to "ALCOHOL" and the rest of the columns would be blank, while the whole row would have a slightly different formatting (bg color and font mostly). Then after the last Product of type 'Alcohol' there would be another row like that , saying 'Food' etc.

Any ideas how could I do this ? As far as I know, a TableView can only represent one class and I cannot create more than one table because I need the fixed column headers functionality when scrolling.

Thanks a lot.

我有麻烦找出如何接近这个:

我想在我的场景图,将代表某一类有一个TableView(产品)。类有一个字符串类型字段,我希望使用它来对产品进行分类。因此,我想在TableView回路中,添加所有的产品,而产品的每一个具体类型之前添加“类别”列。

所以如果我有如10的产品和我们说6的人的类型是“酒精”和“食物”的其他类型的TableView,第一排有它的“名称”列设置为“醇”和其他的柱子都是空白,而整个行有一个稍微不同的格式(背景颜色和字体大多)。然后在最后一个产品的类型'酒精'会有另一行一样,说“食物”等。

我怎么能这么做?据我所知,一个TableView只能代表一类不能创建多个表,因为我需要固定的列标题的功能时,滚动。

谢谢.

answer1: 回答1:

You can do almost all of this with CSS, and then a little magic with a rowFactory on the table and a cell factory that just sets a css class for the cells you want to "hide" for subsequent items of the same type.

In the rowFactory, create a TableRow that observes the list of items in the table, and observes its own index, and sets a CSS PsuedoClass on the row according to whether or not it is the first item of its type:

    PseudoClass firstOfTypePseudoclass = PseudoClass.getPseudoClass("first-of-type");

    table.setRowFactory(t -> {
        TableRow<Product> row = new TableRow<>();
        InvalidationListener listener = obs -> 
            row.pseudoClassStateChanged(firstOfTypePseudoclass, 
                    isFirstOfType(table.getItems(), row.getIndex()));
        table.getItems().addListener(listener);
        row.indexProperty().addListener(listener);
        return row ;
    });

For the column displaying the type, the cell factory implementation is just a standard implementation, but setting a css class on the cell:

    TableColumn<Product, Product.Type> typeColumn = ... ;
    typeColumn.setCellFactory(c -> {
        TableCell<Product, Product.Type> cell = new TableCell<Product, Product.Type>() {
            @Override
            public void updateItem(Product.Type type, boolean empty) {
                super.updateItem(type, empty);
                if (type == null) {
                    setText(null);
                } else {
                    setText(type.toString());
                }
            }
        };
        cell.getStyleClass().add("type-cell");
        return cell ;
    });

Then attach an external style sheet. You can style the table-row-cell:first-of-type any way you want. Then just style cells in the type column to be invisible unless they are child nodes of table-row-cell:first-of-type:

.table-row-cell:first-of-type {
    -fx-background-color: antiquewhite ;
}
.table-row-cell:first-of-type:odd {
    -fx-background-color: derive(antiquewhite, 20%);
}
.table-row-cell .type-cell {
    visibility: hidden ;
}
.table-row-cell:first-of-type .type-cell {
    visibility: visible ;
}

With that style sheet saved as first-of-type-table.css, the following complete example does what you are looking for:

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.css.PseudoClass;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class FirstOfTypeTableExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        TableView<Product> table = new TableView<>() ;

        ObservableList<Product> products = FXCollections.observableArrayList();
        table.setItems(new SortedList<>(products, Comparator.comparing(Product::getType)));

        TableColumn<Product, Product.Type> typeColumn = column("Type", Product::typeProperty);
        typeColumn.setCellFactory(c -> {
            TableCell<Product, Product.Type> cell = new TableCell<Product, Product.Type>() {
                @Override
                public void updateItem(Product.Type type, boolean empty) {
                    super.updateItem(type, empty);
                    if (type == null) {
                        setText(null);
                    } else {
                        setText(type.toString());
                    }
                }
            };
            cell.getStyleClass().add("type-cell");
            return cell ;
        });

        table.getColumns().add(typeColumn);
        table.getColumns().add(column("Name", Product::nameProperty));
        table.getColumns().add(column("Price", Product::priceProperty));

        PseudoClass firstOfTypePseudoclass = PseudoClass.getPseudoClass("first-of-type");

        table.setRowFactory(t -> {
            TableRow<Product> row = new TableRow<>();
            InvalidationListener listener = obs -> 
                row.pseudoClassStateChanged(firstOfTypePseudoclass, 
                        isFirstOfType(table.getItems(), row.getIndex()));
            table.getItems().addListener(listener);
            row.indexProperty().addListener(listener);
            return row ;
        });

        products.addAll(
                new Product("Chips", 1.99, Product.Type.FOOD),
                new Product("Ice Cream", 3.99, Product.Type.FOOD),
                new Product("Beer", 8.99, Product.Type.DRINK),
                new Product("Laptop", 1099.99, Product.Type.OTHER));

        GridPane editor = createEditor(products);

        BorderPane root = new BorderPane(table, null, null, editor, null) ;
        Scene scene = new Scene(root, 600, 400);
        scene.getStylesheets().add("first-of-type-table.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private boolean isFirstOfType(List<Product> products, int index) {
        if (index < 0 || index >= products.size()) {
            return false ;
        }
        if (index == 0) {
            return true ;
        }
        if (products.get(index).getType().equals(products.get(index-1).getType())) {
            return false ;
        } else {
            return true ;
        }
    }

    private GridPane createEditor(ObservableList<Product> products) {
        ComboBox<Product.Type> typeSelector = new ComboBox<>(FXCollections.observableArrayList(Product.Type.values()));
        TextField nameField = new TextField();
        TextField priceField = new TextField();
        Button add = new Button("Add");
        add.setOnAction(e -> {
            Product product = new Product(nameField.getText(), 
                    Double.parseDouble(priceField.getText()), typeSelector.getValue());
            products.add(product);
            nameField.setText("");
            priceField.setText("");
        });

        GridPane editor = new GridPane();
        editor.addRow(0, new Label("Type:"), typeSelector);
        editor.addRow(1, new Label("Name:"), nameField);
        editor.addRow(2, new Label("Price:"), priceField);
        editor.add(add, 3, 0, 2, 1);

        GridPane.setHalignment(add, HPos.CENTER);
        ColumnConstraints leftCol = new ColumnConstraints();
        leftCol.setHalignment(HPos.RIGHT);
        leftCol.setHgrow(Priority.NEVER);

        editor.getColumnConstraints().addAll(leftCol, new ColumnConstraints());
        editor.setHgap(10);
        editor.setVgap(5);
        return editor;
    }


    private <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
        TableColumn<S, T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
        return col ;
    }


    public  static class Product {


        public enum Type {FOOD, DRINK, OTHER }

        private final ObjectProperty<Type> type = new SimpleObjectProperty<>();
        private final StringProperty name = new SimpleStringProperty();
        private final DoubleProperty price = new SimpleDoubleProperty();

        public Product(String name, double price, Type type) {
            setName(name);
            setPrice(price);
            setType(type);
        }

        public final StringProperty nameProperty() {
            return this.name;
        }
        public final java.lang.String getName() {
            return this.nameProperty().get();
        }
        public final void setName(final java.lang.String name) {
            this.nameProperty().set(name);
        }
        public final DoubleProperty priceProperty() {
            return this.price;
        }
        public final double getPrice() {
            return this.priceProperty().get();
        }
        public final void setPrice(final double price) {
            this.priceProperty().set(price);
        }
        public final ObjectProperty<Type> typeProperty() {
            return this.type;
        }
        public final FirstOfTypeTableExample.Product.Type getType() {
            return this.typeProperty().get();
        }
        public final void setType(final FirstOfTypeTableExample.Product.Type type) {
            this.typeProperty().set(type);
        }


    }


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

你可以做几乎所有的CSS,然后小魔桌上一rowfactory和电池厂,只设置一个CSS类的细胞要“隐藏”为后续同类型项目。

在rowfactory,创造,观察表中的项列表TableRow,观察自己的指数,并设置行的CSS psuedoclass根据它是否是第一个同类型的项目:

    PseudoClass firstOfTypePseudoclass = PseudoClass.getPseudoClass("first-of-type");

    table.setRowFactory(t -> {
        TableRow<Product> row = new TableRow<>();
        InvalidationListener listener = obs -> 
            row.pseudoClassStateChanged(firstOfTypePseudoclass, 
                    isFirstOfType(table.getItems(), row.getIndex()));
        table.getItems().addListener(listener);
        row.indexProperty().addListener(listener);
        return row ;
    });

该列的显示类型,细胞工厂的实现是一个标准的实施,但设置一个CSS类的细胞:

    TableColumn<Product, Product.Type> typeColumn = ... ;
    typeColumn.setCellFactory(c -> {
        TableCell<Product, Product.Type> cell = new TableCell<Product, Product.Type>() {
            @Override
            public void updateItem(Product.Type type, boolean empty) {
                super.updateItem(type, empty);
                if (type == null) {
                    setText(null);
                } else {
                    setText(type.toString());
                }
            }
        };
        cell.getStyleClass().add("type-cell");
        return cell ;
    });

然后附加外部样式表。您可以将表格行单元格样式化:首先键入您所需要的任何类型。然后,类型列中的样式单元格是不可见的,除非它们是表行单元格的子节点:第一类型:

.table-row-cell:first-of-type {
    -fx-background-color: antiquewhite ;
}
.table-row-cell:first-of-type:odd {
    -fx-background-color: derive(antiquewhite, 20%);
}
.table-row-cell .type-cell {
    visibility: hidden ;
}
.table-row-cell:first-of-type .type-cell {
    visibility: visible ;
}

这个样式表保存为first-of-type-table.css,下面的完整的例子是你寻找的东西:

import java.util.Comparator;
import java.util.List;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.InvalidationListener;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.SortedList;
import javafx.css.PseudoClass;
import javafx.geometry.HPos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.ColumnConstraints;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;
import javafx.stage.Stage;

public class FirstOfTypeTableExample extends Application {

    @Override
    public void start(Stage primaryStage) {
        TableView<Product> table = new TableView<>() ;

        ObservableList<Product> products = FXCollections.observableArrayList();
        table.setItems(new SortedList<>(products, Comparator.comparing(Product::getType)));

        TableColumn<Product, Product.Type> typeColumn = column("Type", Product::typeProperty);
        typeColumn.setCellFactory(c -> {
            TableCell<Product, Product.Type> cell = new TableCell<Product, Product.Type>() {
                @Override
                public void updateItem(Product.Type type, boolean empty) {
                    super.updateItem(type, empty);
                    if (type == null) {
                        setText(null);
                    } else {
                        setText(type.toString());
                    }
                }
            };
            cell.getStyleClass().add("type-cell");
            return cell ;
        });

        table.getColumns().add(typeColumn);
        table.getColumns().add(column("Name", Product::nameProperty));
        table.getColumns().add(column("Price", Product::priceProperty));

        PseudoClass firstOfTypePseudoclass = PseudoClass.getPseudoClass("first-of-type");

        table.setRowFactory(t -> {
            TableRow<Product> row = new TableRow<>();
            InvalidationListener listener = obs -> 
                row.pseudoClassStateChanged(firstOfTypePseudoclass, 
                        isFirstOfType(table.getItems(), row.getIndex()));
            table.getItems().addListener(listener);
            row.indexProperty().addListener(listener);
            return row ;
        });

        products.addAll(
                new Product("Chips", 1.99, Product.Type.FOOD),
                new Product("Ice Cream", 3.99, Product.Type.FOOD),
                new Product("Beer", 8.99, Product.Type.DRINK),
                new Product("Laptop", 1099.99, Product.Type.OTHER));

        GridPane editor = createEditor(products);

        BorderPane root = new BorderPane(table, null, null, editor, null) ;
        Scene scene = new Scene(root, 600, 400);
        scene.getStylesheets().add("first-of-type-table.css");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private boolean isFirstOfType(List<Product> products, int index) {
        if (index < 0 || index >= products.size()) {
            return false ;
        }
        if (index == 0) {
            return true ;
        }
        if (products.get(index).getType().equals(products.get(index-1).getType())) {
            return false ;
        } else {
            return true ;
        }
    }

    private GridPane createEditor(ObservableList<Product> products) {
        ComboBox<Product.Type> typeSelector = new ComboBox<>(FXCollections.observableArrayList(Product.Type.values()));
        TextField nameField = new TextField();
        TextField priceField = new TextField();
        Button add = new Button("Add");
        add.setOnAction(e -> {
            Product product = new Product(nameField.getText(), 
                    Double.parseDouble(priceField.getText()), typeSelector.getValue());
            products.add(product);
            nameField.setText("");
            priceField.setText("");
        });

        GridPane editor = new GridPane();
        editor.addRow(0, new Label("Type:"), typeSelector);
        editor.addRow(1, new Label("Name:"), nameField);
        editor.addRow(2, new Label("Price:"), priceField);
        editor.add(add, 3, 0, 2, 1);

        GridPane.setHalignment(add, HPos.CENTER);
        ColumnConstraints leftCol = new ColumnConstraints();
        leftCol.setHalignment(HPos.RIGHT);
        leftCol.setHgrow(Priority.NEVER);

        editor.getColumnConstraints().addAll(leftCol, new ColumnConstraints());
        editor.setHgap(10);
        editor.setVgap(5);
        return editor;
    }


    private <S,T> TableColumn<S,T> column(String title, Function<S, ObservableValue<T>> property) {
        TableColumn<S, T> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> property.apply(cellData.getValue()));
        return col ;
    }


    public  static class Product {


        public enum Type {FOOD, DRINK, OTHER }

        private final ObjectProperty<Type> type = new SimpleObjectProperty<>();
        private final StringProperty name = new SimpleStringProperty();
        private final DoubleProperty price = new SimpleDoubleProperty();

        public Product(String name, double price, Type type) {
            setName(name);
            setPrice(price);
            setType(type);
        }

        public final StringProperty nameProperty() {
            return this.name;
        }
        public final java.lang.String getName() {
            return this.nameProperty().get();
        }
        public final void setName(final java.lang.String name) {
            this.nameProperty().set(name);
        }
        public final DoubleProperty priceProperty() {
            return this.price;
        }
        public final double getPrice() {
            return this.priceProperty().get();
        }
        public final void setPrice(final double price) {
            this.priceProperty().set(price);
        }
        public final ObjectProperty<Type> typeProperty() {
            return this.type;
        }
        public final FirstOfTypeTableExample.Product.Type getType() {
            return this.typeProperty().get();
        }
        public final void setType(final FirstOfTypeTableExample.Product.Type type) {
            this.typeProperty().set(type);
        }


    }


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