Java 由于绑定而加载FXML时发生IndexOutOfBoundsException

Java 由于绑定而加载FXML时发生IndexOutOfBoundsException,java,javafx,binding,Java,Javafx,Binding,我正在构建一个JavaFX应用程序,并且正在使用bingings。一切正常,但这一行抛出了一个异常 ExportarControlador.class: //List of loaded images, it contains information to find the real image file private ObservableList<ImgBean> list; //Indicator to mark which image from the list shoul

我正在构建一个JavaFX应用程序,并且正在使用bingings。一切正常,但这一行抛出了一个异常

ExportarControlador.class

//List of loaded images, it contains information to find the real image file
private ObservableList<ImgBean> list;

//Indicator to mark which image from the list should be displayed now
private SimpleIntegerProperty indicator;

@FXML private ImageView imageView;

//...

@Override
public void initialize(URL arg0, ResourceBundle arg1){

    //...   

    imageView.imageProperty().bind(Bindings.when(
                Bindings.isEmpty(list))
                .then(new SimpleObjectProperty<ImgBean>())
                .otherwise(new SimpleObjectProperty<ImgBean>(new Image(someUtils.getURLFromImgBean(list.get(indicator.get()))))));

    //...
}

显然,异常的原因是调用了
。否则()
,但它没有意义,因为除非单击填充列表的按钮,否则列表总是空的,因此
。然后()
应该是唯一调用的方法

我没有正确绑定
。否则()
?我是否错过了其他更简单的方法来实现同样的结果?谢谢。

绑定。when(…)fluent API不作为快捷方式操作符:换句话说,它将计算
否则()
子句,即使
when()
子句中的条件为true(反之,将计算
then()
子句,即使
when()
子句为false)

相反,您可以直接创建自定义绑定:

imageView.imageProperty().bind(Bindings.createObjectBinding(() -> {
    if (list.isEmpty()) {
        return null ;
    } else {
        int index = indicator.get();
        ImgBean imgBean = list.get(index);
        URL imageUrl = someUtils.getURLFromImgBean(imgBean);
        return new Image(imageUrl);
    }
}, list, indicator);
如果需要的话,您还可以很容易地使用它来检查索引是否在边界内

imageView.imageProperty().bind(Bindings.createObjectBinding(() -> {
    if (list.isEmpty()) {
        return null ;
    } else {
        int index = indicator.get();
        ImgBean imgBean = list.get(index);
        URL imageUrl = someUtils.getURLFromImgBean(imgBean);
        return new Image(imageUrl);
    }
}, list, indicator);