【问题标题】:JavaFX 2. Loading external CSV into a TableViewJavaFX 2. 将外部 CSV 加载到 TableView
【发布时间】:2012-11-27 20:38:42
【问题描述】:

我对 Java 很陌生,我正在 Internet 上搜索一种将外部 csv 加载到 JavaFX TableView 中的简单方法。 我能够将 CSV 解析为一个数组,但我现在不知道如何处理它。然后我在玩 DataFX 库。但是再次无法将解析的 csv 传递到我的表中。 我想我在这里不太了解 ObservableLists 我认为这是必要的吗?你知道一个很好的教程,或者你能解释一下解析文件后的下一步是什么吗? 谢谢

编辑:这就是我所做的

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 {  
  @SuppressWarnings("unchecked")  
  @Override  
  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");  
       @SuppressWarnings("rawtypes")  
       TableView table1 = new TableView();  
       TableColumn<?, ?> orderCol = dataSource.getNamedColumn("order-id");  
       TableColumn<?, ?> itemCol = dataSource.getNamedColumn("order-item-id");    
       table1.getColumns().addAll(orderCol, itemCol);  
       table1.setItems(dataSource);  
       stage.setScene(SceneBuilder.create().root(table1).build());  
       stage.show();  
  }  
  public static void main(String[] args) {  
       Application.launch(args);  
  }  
}  

eclipse 说 for table1.setItems(dataSource);

TableView 类型中的方法 setItems(ObservableList) 不适用于参数(CSVDataSource)

【问题讨论】:

标签: csv tableview javafx


【解决方案1】:

有一个sample solution here 用于制表符分隔的文件。 csv 文件也可以类似处理。

该示例通过将TableView 的类型声明为TableView&lt;ObservableList&lt;StringProperty&gt;&gt; 来工作,这样TableView 中的每一行都是字符串属性的ObservableList,其中每个属性都代表csv 文件中的一个字段。 TableViewitems 列表是此类列表的列表。为每一列设置的cellValueFactorys 从支持该单元格行的ObservableList&lt;StringProperty&gt; 中提取该列的正确单元格值。

【讨论】:

    【解决方案2】:

    TableView 类型中的方法 setItems(ObservableList) 不是 适用于参数(CSVDataSource)

    换行

    table1.setItems(dataSource);
    

    table1.setItems(dataSource.getData());
    

    使用 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();
    tableView.setItems(ds1.getData());
    tableView.getColumns().addAll(ds1.getColumns());
    

    如果您想以标准 javafx 方式进行操作:Look Here

    【讨论】:

    • 这仍然是 datafx 中的一个类吗??
    • @JasonWeh 我不知道,这些天我没有用 javafx 开发,请用最新的代码编辑它:)
    • 从我的编译错误来看,快速搜索不再存在
    猜你喜欢
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-04
    • 2015-12-13
    • 2011-11-05
    • 1970-01-01
    相关资源
    最近更新 更多