How to add rows and columns to JavaFX 8 tableview

I saw an example of adding rows to tableview on the Internet, such as using the person class in Oracle documentation

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

The Oracle example continues to show how to bind columns to attribute names, but for this purpose, it only shows how to add columns, not rows

My question is, can anyone point to a Hello, world example and dynamically add any columns and / or rows to JavaFX 8 tableview?

Solution

Use list < string > (for example) for data types, just set the cell value factory as a callback indexed to the list

For example, this will create a tableview < list < string > > which is composed of any tab delimited text file Not all lines in the file need to have the same number of elements (it will fill in blanks) (it does not support escape tags, 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 ;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>