Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Last active June 9, 2018 16:26
Show Gist options
  • Select an option

  • Save thomasnield/c227e00f4ae03e9a139cf09e47523d6c to your computer and use it in GitHub Desktop.

Select an option

Save thomasnield/c227e00f4ae03e9a139cf09e47523d6c to your computer and use it in GitHub Desktop.
JavaFX DirtyObservableList, DirtyObservableSet, and DirtyObjectProperty
import javafx.beans.property.SimpleBooleanProperty
import javafx.beans.value.ObservableValue
import javafx.collections.FXCollections
import javafx.collections.ObservableList
import javafx.collections.ObservableSet
import javafx.collections.SetChangeListener
import tornadofx.*
class DirtyObservableList<T>(originalList: List<T> = listOf()):
ObservableList<T> by FXCollections.observableArrayList<T>(originalList) {
private val originalList = FXCollections.observableArrayList<T>(originalList)
private val _isDirtyProperty = SimpleBooleanProperty()
private var _isDirty by _isDirtyProperty
/** Sets this `ObservableList` to now be the "original" list **/
fun rebaseline() {
originalList.setAll(this)
_isDirty = false
}
/** Resets this `ObservableList` to the "original" list **/
fun reset() {
setAll(originalList)
_isDirty = false
}
init {
onChange {
_isDirty = originalList != this
}
}
fun isDirtyProperty(): ObservableValue<Boolean> = _isDirtyProperty
val isDirty get() = _isDirty
}
class DirtyObservableSet<T>(originalSet: Set<T> = setOf()):
ObservableSet<T> by FXCollections.observableSet(HashSet<T>(originalSet)) {
private val originalSet = FXCollections.observableSet(HashSet<T>(originalSet))
private val _isDirtyProperty = SimpleBooleanProperty()
private var _isDirty by _isDirtyProperty
fun rebaseline() {
originalSet.clear()
originalSet.addAll(this)
_isDirty = false
}
fun reset() {
clear()
addAll(originalSet)
_isDirty = false
}
init {
addListener(
SetChangeListener<T> {
_isDirty = originalSet != this
}
)
}
fun isDirtyProperty(): ObservableValue<Boolean> = _isDirtyProperty
val isDirty get() = _isDirty
}
class DirtyObjectProperty<T>(initialValue: T): Property<T> by SimpleObjectProperty(initialValue) {
private var originalValue = initialValue
private val _isDirtyProperty = SimpleBooleanProperty(false)
private var _isDirty by _isDirtyProperty
init {
onChange {
_isDirty = originalValue != value
}
}
/** Sets the current value to now be the "original" value **/
fun rebaseline() {
originalValue = value
_isDirty = false
}
/** Resets the current value to the "original" value **/
fun reset() {
value = originalValue
_isDirty = false
}
fun isDirtyProperty(): ObservableValue<Boolean> = _isDirtyProperty
val isDirty get() = _isDirty
}
@eugener

eugener commented Jun 9, 2018

Copy link
Copy Markdown

Great work! All these classes seem to have few things in common - may be a common interface?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment