JavaFX 2. Loading external CSV into a TableView


Im pretty new to Java and Im searching the Internet for a simple way to load an external csv into JavaFX TableView. I was able to parse the CSV into an array but I dont know how I have to handle it now. Then I was playing with the DataFX library. But again wasnt able to pass the parsed csv into my table. I think I dont really understand ObservableLists here which I believe is kind of necessary? Do you know a good tutorial or could you explain what the next steps would be after parsing the file? thx

Edit: That's what I did

import javafx.application.Application;  
import javafx.scene.SceneBuilder;  
import javafx.scene.control.TableColumn;  
import javafx.scene.control.TableView;  
import javafx.stage.Stage;  
import org.javafxdata.datasources.reader.FileSource;  
import org.javafxdata.datasources.provider.CSVDataSource; 

public class CSVTableSample extends Application {  
  public void start(Stage stage) throws Exception {  
       stage.setTitle("Test App");  
       // Just loading the file...  
       FileSource fs = new FileSource("test.csv");  
       // Now creating my datasource 
       CSVDataSource dataSource = new CSVDataSource(  
                 fs, "order-id", "order-item-id");  
       TableView table1 = new TableView();  
       TableColumn<?, ?> orderCol = dataSource.getNamedColumn("order-id");  
       TableColumn<?, ?> itemCol = dataSource.getNamedColumn("order-item-id");    
       table1.getColumns().addAll(orderCol, itemCol);  
  public static void main(String[] args) {  

eclipse says for table1.setItems(dataSource);

The method setItems(ObservableList) in the type TableView is not applicable for the arguments (CSVDataSource)

12/11/2012 6:52:55 PM

Accepted Answer

There is a sample solution here for a tab delimited file. A csv file could handled similarly.

The sample works by declaring the type of the the TableView as TableView<ObservableList<StringProperty>> such that each row in the TableView is an ObservableList of string properties where each property represents a field in the csv file. The TableView's items list is a list of such lists. cellValueFactorys set for each column extract the correct cell value for that column from the ObservableList<StringProperty> backing that cell's row.

12/11/2012 10:00:51 PM

The method setItems(ObservableList) in the type TableView is not applicable for the arguments (CSVDataSource)

change your line




Example Code Using DataFX :

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();

if you want to do it in standard javafx way : Look Here

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