【问题标题】:Using Map with TableView in JavaFX在 JavaFX 中使用带有 TableView 的 Map
【发布时间】:2018-06-11 18:37:51
【问题描述】:

我正在尝试在 JavaFX 的 TableView 中显示地图。下面的代码工作得很好,但我遇到的问题是初始化后任何未来地图的更新都不会显示在 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 中。

【问题讨论】:

    标签: java javafx tableview


    【解决方案1】:

    使用 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()));
    

    【讨论】:

    • 你好,我在哪里添加那行代码?我需要改变什么吗?为了其他人,你能用一些 cmets 或解释来更新你的答案吗?
    • 我用覆盖取出了 2 个语句并添加了你的行,但它不起作用。
    猜你喜欢
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 2017-05-24
    • 2020-10-03
    • 2012-05-20
    相关资源
    最近更新 更多