drenda
drenda

Reputation: 6254

JavaFx ObservableSet adapter

I've a JavaFx client. I'm using as model a bean that has a ObservableSet as field. I want display these data into a ListView and I can't change the kind of my field to a ObservableList.

I think I should write a sort of adapter in order to adapt my ObservableSet to a ObservableList (because ListView requires that).

Using ObservableList the code is:

listView.setItems(myBean.getMyEntitiesList());

I need to set items in the same manner because the data list cames lazy from the server so I need that the Ui updates when data arrives.

Someone is able to give me some idea on how implements such kind of adapter?

Upvotes: 2

Views: 545

Answers (1)

James_D
James_D

Reputation: 209684

You can add a listener to the set and update the list when it changes:

ObservableList<T> items = FXCollections.observableArrayList(myBean.getMyEntitiesList());

myBean.getMyEntitiesList().addListener((Change<? extends T> change) -> {
    if (change.wasAdded()) {
        items.add(change.getElementAdded());
    }
    if (change.wasRemoved()) {
        items.remove(change.getElementRemoved());
    }
});

listView.setItems(items);

Obviously replace T with whatever the actual type of the elements in your list/set are.

Upvotes: 3

Related Questions