JavaFX:CellValueFactory绑定

时间:2016-12-25 20:03:34

标签: javafx

作为我的问题FXML: Bind to nested field的延续,我有多个列,我想设置他们的result避免重复代码,这是我尝试过的:

CellValueFactory

但是我的字段是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); }); } 所以有解决方法吗?

1 个答案:

答案 0 :(得分:2)

不是将字段名称作为String传递,而是传递检索它的函数:

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);
    });
}

然后用类似

的方式调用它
TableColumn<Item, String> nameColumn = ... ;

bindTableColumn(nameColumn, Item::getName);