Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to call next() if using foreach to iterate over Change in JavaFX?

Tags:

java

javafx-8

To listen ObservableList I am using the following code in listener:

@Override
public void onChanged(ListChangeListener.Change<? extends MyClass> c) {
    for(MyClass s : c.getAddedSubList()) {
        // process s
    }
}

unfortunately, I am getting a lot of exceptions:

java.lang.IllegalStateException: Invalid Change state: next() must be called before inspecting the Change.

Should I call next() before my loop? But this contradicts the statement from ListChangeListener javadoc saying getList() should work at any time, and that getAddedSubList() is just a shortcut of getList() expression.

like image 798
Suzan Cioc Avatar asked Nov 15 '25 13:11

Suzan Cioc


1 Answers

A change event may be fired for a single event that cannot be represented by a single set of results from ListChangeListener.Change.getXXX() methods. (For example, if you call setAll(...) on your observable list, under some circumstances.) To account for such changes you have to iterate through a collection of "change representations", getting the information for each of them. The proper idiom to use is

@Override
public void onChanged(ListChangeListener.Change<? extends MyClass> c) {
    while (c.next()) {
        if (c.wasAdded()) {
            for(MyClass s : c.getAddedSubList()) {
                // process s
            }
        }
    }
}
like image 101
James_D Avatar answered Nov 17 '25 09:11

James_D