简体   繁体   中英

Using Map with TableView in JavaFX

I am trying display a Map in TableView in JavaFX. The code below works just fine but the issue I am having is that any future Map's update after initialize doesn't show in the 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);

}

Now, if I try to update the map, this update won't show in the TableView.

use 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()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM