Ayoub.A
Ayoub.A

Reputation: 2113

JavaFX: CellValueFactory binding

As a continuation of my question FXML: Bind to nested field, I hava multiple columns, and I would like to set their CellValueFactory avoiding repetitive code, here is what I tried:

public static <T> void BindTableColumn(TableColumn<T, String> column, String fieldName){
    column.setCellValueFactory(data ->{
        String value = "";
        T model = data.getValue();
        if(model == null){
            value = null;
        }else{
            try {
                value = model.getClass().getField(fieldName).get(new String()).toString();
            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
                    | SecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return new SimpleStringProperty(value);
    });
}

But my fields are private so is there a work around?

Upvotes: 1

Views: 380

Answers (1)

James_D
James_D

Reputation: 209724

Instead of passing the name of the field as a String, pass a function retrieving it:

public static <T> void bindTableColumn(TableColumn<T, String> column, Function<T,String> field){
    column.setCellValueFactory(data ->{
        String value ;
        T model = data.getValue();
        if(model == null){
            value = null;
        }else{
            value = field.apply(model);
        }
        return new SimpleStringProperty(value);
    });
}

and then invoke it with something like

TableColumn<Item, String> nameColumn = ... ;

bindTableColumn(nameColumn, Item::getName);

Upvotes: 2

Related Questions