【问题标题】:How to add rows to TableView without having any data model如何在没有任何数据模型的情况下向 TableView 添加行
【发布时间】:2017-08-08 01:28:00
【问题描述】:

我对 javafx 还很陌生,所以如果我的问题不清楚,请多多包涵。我有一个需要使用 ObservableList 填充的 TableView。

下面的代码使用从 Map 生成的数组列表填充我的“数据”,而这些数组列表又用于向我的表中添加行。

TableView<ArrayList> table = new TableView<>();

ObservableList<ArrayList> data = FXCollections.observableArrayList();

     for(int i=0;i<listSelectedVerticesIds.size();i++){
          ArrayList<String> tempString = new ArrayList<>();
                for(Map.Entry<String,String> temp2 : mapVertex.get(listSelectedVerticesIds.get(i)).entrySet()){
                    tempString.add(temp2.getValue());
                }
                data.add(tempString);           
            }
    table.setItems(data);

但是,我没有看到用“数据”中的列表填充的表格。我猜这是因为没有数据绑定(使用 setCellValueFactory)。但是,如您所见,我没有数据模型类。我的所有数据都来自 Map 作为字符串,我想将其填充到我的 tableview 中。

请提出建议。

【问题讨论】:

  • 我从这段代码中假设一行数据由 observablelist 中的 arraylist 表示?这意味着您的表格视图将是这样的: TableView> 对吗?
  • 是的,一行数据就是一个ArrayList。基本上,在代码中, tempString 具有一行数据的值。我将多个 tempString ArrayList 添加到“数据”中,用于多行。
  • 你能发布你的表格列和它们的单元格值工厂吗?

标签: javafx-8


【解决方案1】:

这是一种非常有效的简单方法。您不需要数据结构来填充表。您只会看到这一点,因为这是大多数示例所显示的。从数据库或文件中填充表是非常常见的用例。我不明白为什么很难找到例子。好吧,希望这会有所帮助。

private TableView<ObservableList<StringProperty>> table = new TableView<>();
private ArrayList<String> myList = new ArrayList<>();

private void updateTableRow() {
    for (int row = 0; row < numberOfRows; row++) {
        ObservableList<StringProperty> data = FXCollections.observableArrayList();
        for (int column = 0; column < numberOfColumns; column++) {
            data.add(column, new SimpleStringProperty(myList.get(row + (column * numberOfRows))));
        }
        table.getItems().add(data);
    }
}

【讨论】:

    猜你喜欢
    • 2011-07-12
    • 2023-03-29
    • 1970-01-01
    • 2012-07-09
    • 2016-05-28
    • 2023-03-16
    • 2020-02-02
    • 2013-09-12
    • 1970-01-01
    相关资源
    最近更新 更多