JavaFX TableView dynamic column and data values


Question

I'm testing myself with a simple CSV Viewer using JavaFX and I'm stuck at populating the table data. I do create the columns dynamically, but the data values are a no-go. I searched the web and found a few ways but all ways include a ObservableList with a custom class (including get/set), which in a CSV Viewer must be dynamically (The CSV can have any number of columns, and that means any number of data values).

Example:

List<String> columns;
List<List<String>> data;

/* Fills 'columns' and 'data' */
parseCSV("C:/list.csv");

int columnIndex = 0;
TableColumn [] tableColumns = new TableColumn[columns.size()];        
for(String columName : columns) {
    tableColumns[columnIndex++] = new TableColumn(columName);
}
table1.getColumns().addAll(tableColumns);

for(List<String> dataList : data) {
    table1.setItems(dataList); // Requires an ObservableList!
}
1
7
11/11/2012 7:19:03 PM

Accepted Answer

use DataFX,which will make your job easier :)

Example Code :

DataSourceReader dsr1 = new FileSource("your csv file path");
String[] columnsArray // create array of column names you want to display 
CSVDataSource ds1 = new CSVDataSource(dsr1,columnsArray);
TableView tableView = new TableView();
tableView.setItems(ds1.getData());
tableView.getColumns().addAll(ds1.getColumns());

Reference : Introduction to DataFX

Edit : Standard JavaFX Way

replace your code :

for(List<String> dataList : data) {
    table1.setItems(dataList); // Requires an ObservableList!
}

with

  //  which will make your table view dynamic 
 ObservableList<ObservableList> csvData = FXCollections.observableArrayList(); 

 for(List<String> dataList : data) {
     ObservableList<String> row = FXCollections.observableArrayList();
    for( String rowData : dataList) {
      row.add(rowData); 
  }
   cvsData.add(row); // add each row to cvsData
}

table1.setItems(cvsData); // finally add data to tableview
9
11/12/2012 1:26:59 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon