Skip to content

Instantly share code, notes, and snippets.

@dustinkredmond
Created March 10, 2021 20:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dustinkredmond/4481d42011286084bff707bd15265c3d to your computer and use it in GitHub Desktop.
Save dustinkredmond/4481d42011286084bff707bd15265c3d to your computer and use it in GitHub Desktop.
Class to create a JavaFX TableView from a CSV file
package com.jfxdev.controls;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
public final class CSVTableView extends TableView<String> {
public CSVTableView(String delimiter, File file) throws IOException {
// Get CSV file lines as List
List<String> lines = Files.readAllLines(Paths.get(file.toURI()));
// Get the header row
String[] firstRow = lines.get(0).split(delimiter);
// For each header/column, create TableColumn
for (String columnName : firstRow) {
TableColumn<String, String> column = new TableColumn<>(columnName);
this.getColumns().add(column);
column.setCellValueFactory(cellDataFeatures -> {
String values = cellDataFeatures.getValue();
String[] cells = values.split(delimiter);
int columnIndex = cellDataFeatures.getTableView().getColumns().indexOf(cellDataFeatures.getTableColumn());
if (columnIndex >= cells.length) {
return new SimpleStringProperty("");
} else {
return new SimpleStringProperty(cells[columnIndex]);
}
});
this.setItems(FXCollections.observableArrayList(lines));
// Remove header row, as it will be added to the data at this point
// this only works if we're sure that our CSV file has a header,
// otherwise, we're just deleting data at this point.
this.getItems().remove(0);
}
}
}
@Aladdine95
Copy link

Perfect match for me. Thanks a lot !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment