JavaFX如何在tableView中隐藏空列单元格

时间:2018-04-03 08:02:41

标签: css javafx tableview javafx-8

我正在使用带有UNCONSTRAINED_RESIZE_POLICY的tableView。 我想将所有空列单元格设置为白色背景。

这是当前的观点。

enter image description here

我正在尝试搜索空节点,但即使通过以下代码(测试函数)搜索tableView中包含的所有节点,我也找不到它:

 private void test() {
        ArrayList<Node> nodes = getAllNodes(tableView);
        nodes.forEach(node -> {
            if(node instanceof TableCell) {
                if(((TableCell) node).getText() == null || ((TableCell) node).getText().isEmpty()) {
                    System.out.println(true);
                }
            }
        });
    }

    public static ArrayList<Node> getAllNodes(Parent root) {
        ArrayList<Node> nodes = new ArrayList<Node>();
        addAllDescendents(root, nodes);
        return nodes;
    }

    private static void addAllDescendents(Parent parent, ArrayList<Node> nodes) {
        for (Node node : parent.getChildrenUnmodifiable()) {
            nodes.add(node);
            if (node instanceof Parent)
                addAllDescendents((Parent)node, nodes);
        }
    }

2 个答案:

答案 0 :(得分:1)

使用CSS样式表应用样式以从TableRowCell中删除背景,而是将背景添加到TableCell s:

/* overwrite default row style */
.table-row-cell {
    -fx-background-color: transparent;
    -fx-background-insets: 0;
}

/* apply row style to cells instead */
.table-row-cell .table-cell {
    -fx-background-color: -fx-table-cell-border-color, -fx-background;
    -fx-background-insets: 0, 0 0 1 0;
}

.table-row-cell:odd {
    -fx-background: -fx-control-inner-background-alt;
}

/* fix markup for selected cells/cells in a selected row */
.table-row-cell:filled > .table-cell:selected,
.table-row-cell:filled:selected > .table-cell {
    -fx-background: -fx-selection-bar-non-focused;
    -fx-table-cell-border-color: derive(-fx-background, 20%);
}

.table-view:focused > .virtual-flow > .clipped-container > .sheet > .table-row-cell:filled:selected .table-cell,
.table-view:focused > .virtual-flow > .clipped-container > .sheet > .table-row-cell .table-cell:selected {
    -fx-background: -fx-selection-bar;
}
scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());

注意:现有列之外没有TableCell个。背景应用于TableRowCell 从虚拟化控件中检索单元格也是一个坏主意:

  • 在第一次布局过程中创建单元格。在您运行代码时,它们可能不存在。
  • 与控件交互(例如,通过调整大小,滚动它等等)可能会导致创建其他单元格。您通过遍历场景对之前找到的单元格所做的任何修改都不会自动应用于这些新节点。

答案 1 :(得分:0)

最简单的方法是:

.table-row-cell:empty {
    -fx-background-color: transparent;
}
相关问题