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?
You can do this by replacing String to StringProperty in the List:
@FXML
private TableView<List<StringProperty>> testTable;
then:
TableColumn<List<StringProperty>, String> coll = new TableColumn<>("one");
add the cellValueFactories:
col1.setCellValueFactory(data -> data.getValue().get(0));
col2.setCellValueFactory(data -> data.getValue().get(1));
.
.
and so on.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With