来自 List 的 javafx tableview 数据 [英] javafx tableview data from List

查看:38
本文介绍了来自 List 的 javafx tableview 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaFX 中的 TableView 有问题.

I've got problem with TableView in JavaFX.

从定义了所有字段的现有类创建表很容易.

Creating tables from existing class with all fields defined is easy.

但我想知道是否可以制作表格并从列表中添加数据?

But I'm wondering if it is possible to make table and add data from List?

我做了类似的东西,但它有点不工作.

I've made something like this but it kinda doesn't work.

    @FXML
    private TableView<List<String>> testTable;

    ....


    List<String> list = new ArrayList<>();
    list.add("1hello");
    list.add("1hello2");

    List<String> list2 = new ArrayList<>();
    list2.add("2hello");
    list2.add("2hello2");

    ObservableList<List<String>> lists = FXCollections.observableArrayList();
    lists.add(list);
    lists.add(list2);

    TableColumn<List<String>, String> coll = new TableColumn<>("one");
    coll.setCellValueFactory(new PropertyValueFactory<List<String>,String>(""));
    TableColumn<List<String>, String> coll2 = new TableColumn<>("two");
    coll2.setCellValueFactory(new PropertyValueFactory<List<String>,String>(""));

    testTable.getColumns().add(coll);
    testTable.getColumns().add(coll2);

    lists.forEach(li -> {
        System.out.println("list: " +  li);
        testTable.getItems().add(li);

    }); 

它没有插入任何数据.这样的事情甚至可能吗?

It didn't insert any data. Is something like that even possible?

推荐答案

您可以通过将 List 中的 String 替换为 StringProperty 来实现:

You can do this by replacing String to StringProperty in the List:

@FXML
private TableView<List<StringProperty>> testTable;

然后:

TableColumn<List<StringProperty>, String> coll = new TableColumn<>("one");

添加 cellValueFactories:

add the cellValueFactories:

col1.setCellValueFactory(data -> data.getValue().get(0));
col2.setCellValueFactory(data -> data.getValue().get(1));
.
.

等等.

这意味着列表的第一个元素将在 col1 中使用,列表的第二个元素将在 col2 中使用.

This means the first element of the list will be used in col1, the second element of the list will be used in col2.

然后你可以像这样填充列表:

Then you can populate the list like:

ObservableList<List<StringProperty>> data = FXCollections.observableArrayList();
List<StringProperty> firstRow = new ArrayList<>();
firstRow.add(0, new SimpleStringProperty("Andrew"));
firstRow.add(1, new SimpleStringProperty("Smith"));
.
.
.
data.add(firstRow);
.
.
.
and so on...
table.setItems(data);

这种方式是可行的,但我认为这是一种非常糟糕的做法.

It is doable this way but I would say it is a very bad practice.

这篇关于来自 List 的 javafx tableview 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆