问题
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