Binding hashmap with tableview (JavaFX)

后端 未结 2 684
轻奢々
轻奢々 2020-12-10 17:17

I want to display HashMap contents in a JavaFX Tableview. Please find below the code I used to set the HashMap contents into the tabl

2条回答
  •  时光取名叫无心
    2020-12-10 18:21

    Sergey Grinev; I found a solution, a generic solution for this problem

    public class TableCassaController extends TableView> implements Initializable {
    @FXML   private TableColumn column1;
    @FXML   private TableColumn column2;
    
    
    public TableCassaController(ObservableMap map, String col1Name, String col2Name) {
        System.out.println("Costruttore table");
        TableColumn, K> column1 = new TableColumn<>(col1Name);
        column1.setCellValueFactory(new Callback, K>, ObservableValue>() {
    
            @Override
            public ObservableValue call(TableColumn.CellDataFeatures, 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(p.getValue().getKey());
            }
        });
    
        TableColumn, V> column2 = new TableColumn<>(col2Name);
        column2.setCellValueFactory(new Callback, V>, ObservableValue>() {
    
            @Override
            public ObservableValue call(TableColumn.CellDataFeatures, V> p) {
                // for second column we use value
                return new SimpleObjectProperty(p.getValue().getValue());
            }
        });
    
        ObservableList> items = FXCollections.observableArrayList(map.entrySet());
    
        this.setItems(items);
        this.getColumns().setAll(column1, column2);
    
    }
    

    Very Thanks!!! :-)

提交回复
热议问题