从 JavaFX 动态填充 fxml 中的 TreeTableView

filling TreeTableView in fxml dynamicly from JavaFX

我想动态填充 TreeTableView。我已经使用 Scenebuilder 创建了视图。在 MyController 中,我有一个 Draw 按钮,它通过点击调用一个方法,使它成为一个可树化的对象。我有参考集。当我单击按钮时,只会出现列。应该显示树列的第一列什么也没有显示,列下也没有其他值。当我单独使用它并将其添加到场景时,TreeTableView 可以工作,但现在我想使用这些值来填充由场景生成器制作的 treeTable。还有其他我无法弄清楚的事情。当注释掉 treeTable 注释下的 treeTable = new TreeTableView<>(root); 时,列设置正确!否则也不会显示列。
这就是我想看到的:

package controller;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.stream.Collectors;

import model.DataConstructor;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;

import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeTableCell;
import javafx.scene.control.TreeTableColumn;
import javafx.scene.control.TreeTableView;
import javafx.scene.control.TreeTableColumn.CellDataFeatures;
import javafx.util.Callback;

public class MainController implements Initializable {



private TreeItem<String> root = new TreeItem<>("Functions");
private DataConstructor dc = new DataConstructor();

@FXML
private TreeTableView<String> treeTable;

@Override
public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub

}

public void testDraw(ActionEvent event) {

    drawTable();
}

private void drawTable() {

    root.setExpanded(true);
    Set<String> combinedKeys = new HashSet<>(dc.getCombiFunc().keySet());
    Set<String> funcAllKeys = new HashSet<>(dc.getSortedfuncAll().keySet());
    funcAllKeys.removeAll(dc.getCombiFunc().keySet());
    for (List<String> value : dc.getCombiFunc().values()) {
        funcAllKeys.removeAll(value);
    }
    for (String valueremained : funcAllKeys) {
        ArrayList<String> tempNameId = new ArrayList<>();
        tempNameId.add(dc.getSortedfuncAll().get(valueremained));
        // all elements which are not in combined functions (They are all
        // orphan)
        root.getChildren().add(new TreeItem<String>(tempNameId.get(0)));
    }
    Set<String> keyFromcombined = new HashSet<>();
    List<String> valueOfCombined = new ArrayList<String>();
    for (Entry<String, List<String>> ent : dc.getCombiFunc().entrySet()) {
        valueOfCombined.add(ent.getValue().get(0));
    }
    List<String> rootKeyList = new ArrayList<>();
    for (String key : combinedKeys) {

        if (!valueOfCombined.contains((key))) {

            keyFromcombined.add(dc.getFuncAll().get(key));
            rootKeyList.add(key);
        }
    }
    String[] rootKeys = rootKeyList.toArray(new String[rootKeyList.size()]);

    // ////////////////treetable////////////////////////////

    treeTable = new TreeTableView<>(root);

    Arrays.stream(rootKeys).forEach(
            rootKey -> root.getChildren().add(
                    createTreeItem(dc.getCombiFunc(), rootKey)));

    // ////////////////First column/////////////////////////

    TreeTableColumn<String, String> firstColumn = new TreeTableColumn<>("");
    treeTable.getColumns().add(firstColumn);// Tree column
    firstColumn
            .setCellValueFactory(new Callback<CellDataFeatures<String, String>, ObservableValue<String>>() {
                public ObservableValue<String> call(
                        CellDataFeatures<String, String> p) {
                    return new ReadOnlyStringWrapper(p.getValue()
                            .getValue());
                }
            });

    // //////////////////Rest Columns////////////////////////

    for (Entry<String, String> ent : dc.getSortedAssignedOrg().entrySet()) {

        TreeTableColumn<String, ArrayList<String>> col = new TreeTableColumn<>();
        Label label = new Label(ent.getValue());
        col.setGraphic(label);
        label.setTooltip(new Tooltip(label.getText()));// tooltip for column
                                                        // headers
        col.setPrefWidth(45);
        //cell Value Factory////////////////////////
        col.setCellValueFactory(new Callback<TreeTableColumn.CellDataFeatures<String, ArrayList<String>>, ObservableValue<ArrayList<String>>>() {
            @Override
            public ObservableValue<ArrayList<String>> call(
                    CellDataFeatures<String, ArrayList<String>> param) {
                TreeMap<String, List<String>> temp = (TreeMap<String, List<String>>) dc
                        .getFuncTypeOrg().clone();
                ArrayList<String> result = new ArrayList<>();
                for (int i = 0; i < dc.getFuncTypeOrg().size(); i++) {
                    List<String> list = temp.firstEntry().getValue();
                    String key = temp.firstEntry().getKey();
                    // root.getChildren();
                    if (list.get(1).equals(param.getValue().getValue())
                            && list.get(5).equals(label.getText())) {
                        result.add(0, list.get(2));// weight
                        // //////////////org combi TODO
                        for (Entry<String, Set<String>> ent : dc
                                .getCombiOrg().entrySet()) {
                            if (ent.getKey().contains(col.getText()))
                                for (Set<String> value : dc.getCombiOrg()
                                        .values()) {
                                    if (value.contains(col.getText()))
                                        System.out.println(col.getText());
                                }
                        }
                        // ///////////////org combi
                        if (list.size() > 6) {
                            result.add(1, list.get(list.size() - 1));// color
                            result.add(2, list.get(6));// App component
                        }

                        else
                            result.add("white");
                        result.add("noOrg");

                    } else {
                        temp.remove(key);
                    }

                }

                return new ReadOnlyObjectWrapper<ArrayList<String>>(result);
            }
        });

        // //////////////cellfactory/////////////////////////
        col.setCellFactory(new Callback<TreeTableColumn<String, ArrayList<String>>, TreeTableCell<String, ArrayList<String>>>() {
            @Override
            public TreeTableCell<String, ArrayList<String>> call(
                    TreeTableColumn<String, ArrayList<String>> param) {
                return new TreeTableCell<String, ArrayList<String>>() {
                    public void updateItem(ArrayList<String> item,
                            boolean empty) {
                        super.updateItem(item, empty);

                        if (item == null || empty) {
                            setStyle("");
                            setText("");
                        } else if (item.contains("Green")) {
                            float weightInt = Float.parseFloat(item.get(0));
                            float res = weightInt * 1;
                            String resString = Float.toString(res);
                            this.setStyle("-fx-background-color:green");
                            setTooltip(new Tooltip(item.get(2)));
                            setText(resString);
                        } else if (item.contains("yellow")) {
                            this.setStyle("-fx-background-color:yellow");
                            setTooltip(new Tooltip(item.get(2)));
                            setText("0");
                        } else if (item.contains("white")) {
                            setText("DD");
                        }
                    }
                };
            };

        });

        treeTable.getColumns().add(col);
    }
    // end for col


treeTable.setPrefWidth(1200);
treeTable.setPrefHeight(500);
    treeTable.setShowRoot(false);
    treeTable.setTableMenuButtonVisible(true);
}

/**
 * Create a TreeItem for a TreeView from a set of data given the data and an
 * identified root within the data.
 */
private TreeItem<String> createTreeItem(TreeMap<String, List<String>> data,
        String rootKey) {
    TreeItem<String> item = new TreeItem<>();
    item.setValue(rootKey);
    item.setExpanded(true);

    List<String> childData = data.get(rootKey);
    if (childData != null) {
        childData.stream().map(child -> createTreeItem(data, child))
                .collect(Collectors.toCollection(item::getChildren));
    }

    String valueName = item.getValue();
    //String sorteV = dc.getSortedfuncAll().get(valueName);
    item.setValue((dc.getSortedfuncAll().get(valueName)));
    return item;
}

}

您的 drawTable() 方法创建了一个新的 TreeTableView,但我没有看到您将 TreeTableView 添加到 UI 或删除现有 TreeTableView.

您可能想要替换

treeTable = new TreeTableView<>(root);

treeTable.setRoot(root);