来自List的javafx tableview数据 [英] javafx tableview data from List
问题描述
我在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?
推荐答案
您可以将 String
替换为 StringProperty
在列表中
:
@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屋!