You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.5 KiB

  1. package nova.monadic_sfx.util
  2. import scalafx.beans.property.ObjectProperty
  3. import scalafx.beans.property.ReadOnlyObjectProperty
  4. import scalafx.beans.value.ObservableValue
  5. object Misc {
  6. implicit final class MyRichObservable[A, C](val self: ObservableValue[A, C])
  7. extends AnyVal {
  8. def filter(f: A => Boolean): ReadOnlyObjectProperty[A] =
  9. Method.filter(self)(f)
  10. def filterNull: ReadOnlyObjectProperty[A] = Method.filterNull(self)
  11. }
  12. }
  13. object Method {
  14. type Observable[A] = ObservableValue[A, _]
  15. def filter[B](
  16. a: Observable[B]
  17. )(f: B => Boolean): ReadOnlyObjectProperty[B] = {
  18. val prop = ObjectProperty[B](a.value)
  19. def changeHandler() =
  20. prop.synchronized {
  21. if (f(a.value)) {
  22. prop.value = a.value
  23. }
  24. }
  25. a onChange changeHandler()
  26. prop
  27. }
  28. /**
  29. * Simply creates a new observable that mirrors the source observable but
  30. * doesn't emit null values. JavaFX likes to work with null values in scene
  31. * nodes/properties (shrugs) and observables by default emit null values
  32. * that can cause crashes. ScalaFX does not offer any *fixes* for this
  33. *
  34. * @param a
  35. * @return
  36. */
  37. def filterNull[B](
  38. a: Observable[B]
  39. ): ReadOnlyObjectProperty[B] = {
  40. val prop = ObjectProperty[B](a.value)
  41. def changeHandler() =
  42. prop.synchronized {
  43. if (a.value != null) {
  44. prop.value = a.value
  45. }
  46. }
  47. a onChange changeHandler()
  48. prop
  49. }
  50. }