Search code examples
swingeventsscalascala-swing

How to make own Scala UI Events


I am currently developing my first bigger Scala Swing project, and I have written my own component as a part of the tile map editor, in which the user chooses the tiles.

Just as a combo box emits some sort of event when another element is selected, I want this component to do the same, with my own case classes. I have not found any article or tutorial on this topic.

In further notice, how can I also write a component that publishes the events of sub-components. So that it just reaches them through.


Solution

  • Perhaps look at other projects extending scala-swing. For example there is ScalaSwingContrib; I think looking at the ColorChooser component and the associated ColorChooserEvent is a good starting point, as this is a fairly simple component.

    import javax.{swing => js}
    import js.{event => jse}
    import java.awt.Color
    import scala.swing._
    import event.Event
    
    class ColorChooser(initialColor: Color) extends Component {
      ...
      override lazy val peer: js.JColorChooser = 
        new js.JColorChooser(initialColor) with SuperMixin
    
      peer.getSelectionModel().addChangeListener(new jse.ChangeListener {
        def stateChanged(e: jse.ChangeEvent) {
          publish( new ColorChangeEvent(peer.getColor))
        }
      })
    }
    
    case class ColorChangeEvent(c: Color) extends Event