cascer1 cascer1 - 1 year ago 131
Java Question

ObservableList doesn't update ArrayList

For a school assignment, we're working with ObservableList objects from JavaFX (Right?). I've been working on this for over a day now and can't figure it out. The teacher only tells us to 'Google it' so that's no help either..

Basically, we're working on a basic administration application to keep track of people and their families. Where people are member of a family, and a family can have multiple members.

When a person or family is added, they are added to an observableList which should then update an ArrayList (So the data can be serialized) and a GUI element. This is where the problem is.

We currently have the following implementation:

private List<Persoon> personen;
private List<Gezin> gezinnen;
this.personen = new ArrayList<Persoon>();
this.gezinnen = new ArrayList<Gezin>();

private transient ObservableList<Persoon> observablePersonen;
private transient ObservableList<Gezin> observableGezinnen;
observablePersonen = FXCollections.observableArrayList(personen);
observableGezinnen = FXCollections.observableArrayList(gezinnen);

Then when an item is added, we do the following:

Persoon p = new Persoon();

After this when we inspect the 'personen' list, the added object isn't there :(

Are we missing something obvious?

Answer Source

You need to use FXCollections.observableList instead of FXCollections.observableArrayList.

As per the documentation of observableList:

Constructs an ObservableList that is backed by the specified list.

So any modification of the observable list will be reported to the backing list. However, in the case of observableArrayList:

Creates a new observable array list and adds a content of collection col to it.

so this list is not backed by the given list, it just serves as an initial collection.

As a side note, you should not call notifyAll(): this method has nothing to do with JavaFX and it relates to waking threads waiting on this object.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download