我正在尝试在JavaFX中的TableView中显示Map。下面的代码工作正常,但我遇到的问题是,在初始化之后任何未来的Map更新都不会在TableView中显示。
public class TableCassaController<K,V> extends TableView<Map.Entry<K,V>> implements Initializable {
@FXML private TableColumn<K, V> column1;
@FXML private TableColumn<K, V> column2;
// sample data
Map<String, String> map = new HashMap<>();
map.put("one", "One");
map.put("two", "Two");
map.put("three", "Three");
public TableCassaController(ObservableMap<K,V> map, String col1Name, String col2Name) {
System.out.println("Costruttore table");
TableColumn<Map.Entry<K, V>, K> column1 = new TableColumn<>(col1Name);
column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<K, V>, K>, ObservableValue<K>>() {
@Override
public ObservableValue<K> call(TableColumn.CellDataFeatures<Map.Entry<K, V>, K> p) {
// this callback returns property for just one cell, you can't use a loop here
// for first column we use key
return new SimpleObjectProperty<K>(p.getValue().getKey());
}
});
TableColumn<Map.Entry<K, V>, V> column2 = new TableColumn<>(col2Name);
column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<K, V>, V>, ObservableValue<V>>() {
@Override
public ObservableValue<V> call(TableColumn.CellDataFeatures<Map.Entry<K, V>, V> p) {
// for second column we use value
return new SimpleObjectProperty<V>(p.getValue().getValue());
}
});
ObservableList<Map.Entry<K, V>> items = FXCollections.observableArrayList(map.entrySet());
this.setItems(items);
this.getColumns().setAll(column1, column2);
}
现在,如果我尝试更新地图,则此更新将不会显示在TableView中。
答案 0 :(得分:0)
使用ReadOnlyObjectWrapper
TableColumn<Map.Entry<K, V>, K> column1 = new TableColumn<>(col1Name);
column1.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getKey()));
TableColumn<Map.Entry<K, V>, V> column2 = new TableColumn<>(col2Name);
column2.setCellValueFactory(param -> new ReadOnlyObjectWrapper<>(param.getValue().getValue()));