Connect TableView columns to the HashMap values

只谈情不闲聊 提交于 2019-12-25 08:52:27

问题


I'm writing a simple crud-redactor, and there is a problem I stuck on:

I have a class:

public class Note {
    List<String> columnNames;
    HashMap<String, SimpleStringProperty> items;
}

which I need to somehow connect with a TableView via setCellValueFactory. For example I have 3 values in HashMap with keys "id", "name" and "age". So I want to have 3 columns in TableView which are connected with this HashMap and will represent its values after wrapping an array of Notes into ObservableList and using TableView method setItems().


回答1:


Just use value factories returning the value in the map for a given key, e.g.

final String key = "id";
TableColumn<Note, String> column = new TableColumn<>("ID");
column.setCellValueFactory(cd -> cd.getValue().items.get(key));

In case you need to use the keys from columnNames you could get the property based on the index instead, e.g.

final String index = 1;
TableColumn<Note, String> column = new TableColumn<>("1");
column.setCellValueFactory(cd -> cd.getValue().columnNames.size() <= index ?
                                    null
                                  : cd.getValue().items.get(cd.getValue().columnNames.get(index)));

Note that depending on the package used you may need to add getters to the Note class.


You could also create non-existing properties "on the fly", by using Map.computeIfAbsent instead of get, if that is the desired behaviour:

items.computeIfAbsent(key, k -> new SimpleStringProperty())


来源:https://stackoverflow.com/questions/39506108/connect-tableview-columns-to-the-hashmap-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!