Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javafx tableview data from List

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?

like image 815
Andrew Avatar asked Apr 12 '26 21:04

Andrew


1 Answers

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.

like image 159
Sunflame Avatar answered Apr 15 '26 00:04

Sunflame