ZbyszekKr ZbyszekKr - 7 days ago 6
Scala Question

Notifying ObservableBuffer listeners on content's member change

I have an

ObservableBuffer[T]
that contains a number of elements and
ComboBox[T]
which displays these elements most likely using it's
toString()
method.

Class
T
(for now let's assume it is mutable) has a
name
field which is changed during execution of the program.

However (obviously) this doesn't trigger the
ComboBox
's reloading of the elements and that's a requirement.

Only way around this, that I found is through immutability - deleting the given element from the collection and adding the updated one:

/* Context */
val items: ObservableBuffer[T]
val beforeChange: T

val afterChange: T = beforeChange.changed
items -= beforeChange
items += afterChange


This solution works and immutability is always a good thing so I might go ahead with it, but still curious whether this approach is the only viable way.

Answer

If you can't use immutable items, you could try to construct an observable list using javafx.collections.FXCollections.observableList(List list, Callback extractor). Then use the extractor to notify about the changes to mutable elements. See also Combobox refresh value and listview when object content change.

Comments