cartilage
cartilage

Reputation: 33

Filling a JavaFX TableView with DataFX

I'm trying to fill a TableView with the data from a csv-file with the datafx extension.

Unfortunately the tableview is empty and I'm not able to find any example anywhere which indicates my mistake.

    DataSourceReader dsr1 = new FileSource("Example3.csv");

    CSVDataSource ds1 = new CSVDataSource(dsr1);
    TableView table1 = new TableView();
    table1.setItems(ds1.getData());
    table1.getColumns().addAll(ds1.getColumns());

    System.out.println("#ds1 " + ds1.getData().size());  //returns zero

The code does not throw an exception, which makes it even more mysterious.

Upvotes: 3

Views: 1190

Answers (1)

Ahmed Hasn.
Ahmed Hasn.

Reputation: 330

even though the question is to fill the TableView with the DataFX extension here is a solution without DataFX:

  1. Create a class that represents a list item of your tableView e.g.:

    public class YourItem { 
     private String itemID;
     private String itemTitle;
    
     public String getItemID() {
          return itemID;
     }
    
     public void setitemID(String itemID) {
          this.itemID = itemID;
     }
    
     //getter and setter for the other vars, I am lazy. }
    
  2. Parse your csv file and return a List<YourItem>

    there are several tutorials and examples for that, you can find one here: http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/ Important is that you create a List of YourItem objects where each row is a YourItem object

  3. Convert your List<YourItem> into an ObservableList<YourItem>

ObservableList<YourItem> obsList = FXCollections.observableArrayList(yourList);

  1. finally set the items to your TableView: I won't mention that you need to create Columns for your TableView

    TableView<YourItem> test = new TableView<YourItem>(); test.setItems(obsList);

Upvotes: 2

Related Questions