IndexOutOfBoundsException while updating a ListView in JavaFX

点点圈 提交于 2019-11-28 00:07:22

Bit late, but since you are still getting the exceptions, here's my two cents. I was getting the same error and here's what worked for me.

You can't update UI elements from a non-main thread. One way to do this is make a Runnable and schedule it on the main thread by runLater.

Platform.runLater(new Runnable() {
    @Override public void run() {
//put your code here
}});

Put the observalble list outside of a method (just like a normal field)

ObservableList<Default> listData = FXCollections.observableArrayList()

public void initialize(Url url, ResourceBundle rb) {
    listData.addAll(myService.getFoo);
    listTest.setItems(listData);

    //You could use lambdas here if you use Java8
    listTest.getSelectionModel.selectedItemProperty()
        .addListener(new ChangeListener<Default>(){

            @Override
            public void changed(ObservableValue<? extends Default> observable,
                        Default oldValue, Default newValue) {
                    //Update the graphical simulations somewhere here
                    listData.clear();
                    listData.add(new Default(..)); //Add new values to list
                }
        });
}

If you bind the list to a observable list objects, the table changes whenever the observable list (here listData). What you did wrong create a new observable list every time.

Jupiter

I had exactly the same problem while using a ComboBox and trying to update the backing observablelist.

I fixed it by changing the ComboBox to a ChoiceBox and now I don't get the IndexOutOfBoundsException anymore.

Did you try using other containers?

Xu Li

I think you are in the similar situation of this answer:JavaFX ComboBox change value causes IndexOutOfBoundsException

try

Platform.runLater(() -> updateList(newValue) )

instead of updateList(newValue)

In my case this issue occured when I had ScenicView opened beside my JavaFX application. Closing it solved the problem.

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