Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
636 views
in Technique[技术] by (71.8m points)

arraylist - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...