0
我想加載一個csv文件到我的tableView中,但表中沒有填充這裏是我的代碼。我不知道我在做什麼Javafx TableView無法從observableArrayList加載數據
public class FXMLDocumentController implements Initializable {
File csv;
@FXML
AnchorPane anchorpane;
Stage stage;
@FXML
TableView dataTable;
@FXML
TextField path;
@FXML
public void browseOnClick(){
stage = (Stage) anchorpane.getScene().getWindow();
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open CSV File");
fileChooser.setInitialDirectory(
new File(System.getProperty("user.home"))
);
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Coma separated value", "*.csv")
);
csv = fileChooser.showOpenDialog(stage);
if(csv != null){
open();
}
}
public void open(){
path.setText(csv.getAbsolutePath());
loadCSV(csv, dataTable);
}
public void loadCSV(File csv,TableView table)
{
try {
ObservableList<ObservableList> csvData = FXCollections.observableArrayList();
Scanner sc = new Scanner(csv);
while(sc.hasNext()){
ObservableList<String> row = FXCollections.observableArrayList();
for(String column: sc.nextLine().split(",")){
row.add(column);
}
csvData.add(row);
}
table.getItems().clear();
table.getColumns().clear();
table.setItems(csvData);
createColums(table, csvData.get(0).size());
} catch (FileNotFoundException ex) {
Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void createColums(TableView table,int size){
for(int x = 1; x<size; x++){
TableColumn t = new TableColumn("Paramiter "+x);
t.setPrefWidth(120);
table.getColumns().add(t);
}
TableColumn t = new TableColumn("Target");
t.setPrefWidth(120);
table.getColumns().add(t);
}
@Override
public void initialize(URL url, ResourceBundle rb) {
path.setEditable (false);
}
}
但是當我運行此代碼輸出是一個空表。 columns and rows added but there is no data
它的工作,謝謝 – noshusan