如何向JavaFX 8 TableView添加行和列 [英] How can I add rows and columns to a JavaFX 8 TableView

查看:811
本文介绍了如何向JavaFX 8 TableView添加行和列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上看到了向TableView添加行的示例,例如使用 Oracle文档

I see examples on the internet for adding a row to a TableView, for example using the Person class in the Oracle documentation.

但是我有一个可变数量的列,所以我不能绑定到Person(或任何其他)bean业务对象。

But I have a variable number of columns, so I can't bind to a Person (or any other) bean business object.

Oracle示例继续展示如何将列绑定到属性名称,但为此,它仅显示如何添加列,而不是行。

The Oracle example goes on to show how to bind columns to property names, but for that, it only shows how to add columns, but not rows.

我的问题是,有人可以指向一个Hello,World示例,动态地将任意列和/或行添加到JavaFX 8 TableView中吗?

My question is, can someone point me to a Hello, World example of dynamically adding arbitrary columns and/or rows to a JavaFX 8 TableView?

推荐答案

对数据类型使用 List< String> (例如),然后设置单元格将factory值作为索引到列表中的回调。

Use a List<String> (for example) for the data type, and just set the cell value factory as a callback that indexes into the list.

例如,这将创建一个 TableView< List< String>> 由任意制表符分隔的文本构成文件中。并非文件中的所有行都需要具有相同数量的元素(它将填充空白)。 (它不支持转义标签等):

For example, this will create a TableView<List<String>> that is constructed out of an arbitrary tab-delimited text file. Not all rows in the file need have the same number of elements (it will pad with blanks). (It doesn't support escaped tabs, etc):

public TableView<List<String>> readTabDelimitedFileIntoTable(Path file) throws IOException {
    TableView<List<String>> table = new TableView<>();
    Files.lines(file).map(line -> line.split("\t")).forEach(values -> {
        // Add extra columns if necessary:
        for (int i = table.getColumns().size(); i < values.length; i++) {
            TableColumn<List<String>, String> col = new TableColumn<>("Column "+(i+1));
            col.setMinWidth(80);
            final int colIndex = i ;
            col.setCellValueFactory(data -> {
                List<String> rowValues = data.getValue();
                String cellValue ;
                if (colIndex < rowValues.size()) {
                    cellValue = rowValues.get(colIndex);
                } else {
                     cellValue = "" ;
                }
                return new ReadOnlyStringWrapper(cellValue);
            });
            table.getColumns().add(col);
        }

        // add row:
        table.getItems().add(Arrays.asList(values));
    });
    return table ;
}

这篇关于如何向JavaFX 8 TableView添加行和列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆