I have a TableView
with two columns, a TreeMap<String, String>
and an ObservableMap
. I want to fill the TableView
with my TreeMap
data.
But tableview.setItems(observableMap)
does not work because setItems
expects an ObservableList
. I tried the same with observableHashMap
which also didn't work. What can I do to fill my TableView
with my data in the TreeMap
?
Use the keys as item type for the TableView
and use the cellValueFactory
for the value column to extract the value:
Map<String, String> map = ...
TableView<String> tableView = new TableView();
// fill table with keys
tableView.getItems().addAll(map.keySet());
TableColumn<String, String> keyColumn = new TableColumn<>("key");
keyColumn.setCellValueFactory(cd -> new SimpleStringProperty(cd.getValue()));
TableColumn<String, String> valueColumn = new TableColumn<>("value");
valueColumn.setCellValueFactory(cd -> new SimpleStringProperty(map.get(cd.getValue())));
tableView.getColumns().addAll(keyColumn, valueColumn);
Alternatively you could also use a TableView<Map.Entry<String, String>>
...
// fill table with keys
tableView.getItems().addAll(map.entrySet());
TableColumn<Map.Entry<String, String>, String> keyColumn = new TableColumn<>("key");
keyColumn.setCellValueFactory(new PropertyValueFactory<>("key"));
TableColumn<Map.Entry<String, String>, String> valueColumn = new TableColumn<>("value");
valueColumn.setCellValueFactory(new PropertyValueFactory<>("value"));
...