【发布时间】:2016-09-07 09:31:30
【问题描述】:
我关注了这篇文章
Binding hashmap with tableview (JavaFX)
并创建了一个由 HashMap 中的数据填充的 TableView。
TableView 通过从map.entrySet() 创建一个ObservableList 并将ObservableList 交给TableView 的构造函数,从一个名为map 的HashMap 接收其数据。 (代码如下)
然而,虽然它是 ObservableList 和 SimpleStringPropertys,但当底层 HashMap 发生更改时,TableView 不会更新。
这是我的代码:
public class MapTableView extends Application {
@Override
public void start(Stage stage) throws Exception {
try {
// sample data
Map<String, String> map = new HashMap<>();
map.put("one", "One");
map.put("two", "Two");
map.put("three", "Three");
// use fully detailed type for Map.Entry<String, String>
TableColumn<Map.Entry<String, String>, String> column1 = new TableColumn<>("Key");
column1.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
// this callback returns property for just one cell, you can't use a loop here
// for first column we use key
return new SimpleStringProperty(p.getValue().getKey());
}
});
TableColumn<Map.Entry<String, String>, String> column2 = new TableColumn<>("Value");
column2.setCellValueFactory(new Callback<TableColumn.CellDataFeatures<Map.Entry<String, String>, String>, ObservableValue<String>>() {
@Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<Map.Entry<String, String>, String> p) {
// for second column we use value
return new SimpleStringProperty(p.getValue().getValue());
}
});
ObservableList<Map.Entry<String, String>> items = FXCollections.observableArrayList(map.entrySet());
final TableView<Map.Entry<String,String>> table = new TableView<>(items);
table.getColumns().setAll(column1, column2);
Button changeButton = new Button("Change");
changeButton.setOnAction((ActionEvent e) -> {
map.put("two", "2");
System.out.println(map);
});
VBox vBox = new VBox(8);
vBox.getChildren().addAll(table, changeButton);
Scene scene = new Scene(vBox, 400, 400);
stage.setScene(scene);
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch();
}
}
这正是来自Binding hashmap with tableview (JavaFX) 的代码,除了我添加了以下按钮:
Button changeButton = new Button("Change");
changeButton.setOnAction((ActionEvent e) -> {
map.put("two", "2");
System.out.println(map);
});
然后我将其添加到带有 TableView 的 VBox 中。
当我点击按钮时,TableView 没有更新。但是,我可以验证底层HashMap 确实由于System.out.println(map) 输出而发生了变化。此外,当我单击TableView 中的列标题以按一列对数据进行排序时,重新排序表数据后会出现新的更新值。
如何在基础地图更改时自动更新表?
谢谢,
标记
【问题讨论】:
-
我没有详细研究这个,但也许你想使用ObservableMap。
标签: java javafx hashmap tableview observablelist