Search code examples
swingscalaeventspropertiesjavabeans

How to subscribe to Action property change with scala.swing listenTo?


I have a scala.swing Action with a custom property mydomain.color. I would like to repaint a button which is bound to this Action whenever the property is changed. It should be possible to subscribe to PropertyChangeEvent, however Action is not a Publisher, therefore it cannot be used for listenTo.

It would be possible to do it a normal Java way and to write a Property Change Listener, but is there perhaps some shorter way? Can Java beans be used as Publishers for scala.swing listenTo?


Solution

  • A property change listener can be used to transform the Java beans event into a swing one and publish it, it is not that difficult:

    import scala.swing._
    import scala.swing.event._
    import java.beans.{PropertyChangeListener, PropertyChangeEvent}
    
    case class PropertyChanged(source: AnyRef, propertyName: String, oldValue: AnyRef, newValue: AnyRef) extends Event
    
    trait ActionPropertyPublisher extends Action with Publisher {
      actionPublisher =>
    
      class ListenToPropertyChange extends PropertyChangeListener {
        override def propertyChange(evt: PropertyChangeEvent): Unit = {
          assert(SwingUtilities.isEventDispatchThread)
          assert(evt.getSource==actionPublisher.peer)
          publish(new PropertyChanged(actionPublisher,evt.getPropertyName,evt.getOldValue,evt.getNewValue))
        }
      }
    
      peer.addPropertyChangeListener(new ListenToPropertyChange())
    }