Last active
December 30, 2024 20:58
-
-
Save dustinkredmond/4481d42011286084bff707bd15265c3d to your computer and use it in GitHub Desktop.
Class to create a JavaFX TableView from a CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
The call to setItems() and getItems().remove(0) should not be inside the loop that creates the columns.
@dlemmermann, great catch. I've updated it. Thanks.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perfect match for me. Thanks a lot !