Populate tableview in javafx

放肆的年华 提交于 2019-12-11 11:57:43

问题


I want to populate a TableView in JavaFX. My class is Manual and it has another object like attribute (User). How can I populate a table column with the username from the User object.

columnVanzator.setCellFactory(new Callback<TableColumn<Manual, User>, 
                                                        TableCell<Manual, User>>() {

   @Override
   public TableCell<Manual, User> call(TableColumn<Manual, User> arg0) {
        final TableCell<Manual, User> cell = new TableCell<Manual, User>() {
             @Override
             public void updateItem(final User item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        this.setText("");
                    } 
                    else {
                          this.setText(item.getUsername());
                    }
             }
         };
         return cell;
    } 
});

I received NullPointerException on this.setText(item.getUsername());


回答1:


What you're looking for is not a cellFactory, but a cellValueFactory. A custom cellFactory is used if you the type which is displayed in your Column is more complex than a String or a Number (e.g. a Date, State or even more complex types).

JavaFX' cellValueFactory works best with Properties:

column.setCellValueFactory((p) -> p.getValue().yourContentProperty());

But it looks like you don't have a JavaFX Property for that in your Object, so we have to build a little workaround:

column.setCellValueFactory((p) -> new SimpleStringProperty(p.getValue().getUsername());

I would recommend to build your Model in JavaFX-Style and have Properties inside it. If a value changes inside a Property, the TableView will update the Cell automatically. Same goes for almost every control in JavaFX. But if you don't can or simply don't want to, feel free to use the way above, but keep in mind that value changes won't automatically notify the view!



来源:https://stackoverflow.com/questions/44443305/populate-tableview-in-javafx

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!