Binding hashmap with tableview (JavaFX)

后端 未结 2 692
轻奢々
轻奢々 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 17:59

    1. CellFactory.Callback.call() creates just one cell, not all cells in a loop
    2. Using return from a loop breaks loop execution.

    Take a look at next example, especially comments:

    public class MapTableView extends Application {
    
        @Override
        public void start(Stage stage) {
    
            // sample data
            Map map = new HashMap<>();
            map.put("one", "One");
            map.put("two", "Two");
            map.put("three", "Three");
    
    
            // use fully detailed type for Map.Entry 
            TableColumn, String> column1 = new TableColumn<>("Key");
            column1.setCellValueFactory(new Callback, String>, ObservableValue>() {
    
                @Override
                public ObservableValue call(TableColumn.CellDataFeatures, 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, String> column2 = new TableColumn<>("Value");
            column2.setCellValueFactory(new Callback, String>, ObservableValue>() {
    
                @Override
                public ObservableValue call(TableColumn.CellDataFeatures, String> p) {
                    // for second column we use value
                    return new SimpleStringProperty(p.getValue().getValue());
                }
            });
    
            ObservableList> items = FXCollections.observableArrayList(map.entrySet());
            final TableView> table = new TableView<>(items);
    
            table.getColumns().setAll(column1, column2);
    
            Scene scene = new Scene(table, 400, 400);
            stage.setScene(scene);
            stage.show();
        }
    
        public static void main(String[] args) {
            launch();
        }
    }
    

提交回复
热议问题