Search code examples
swingscalaeventsjbuttonjtextfield

How to modify text field contents in reaction to button click in Scala Swing?


My dialog window consists of a text field and a button. I would like an arbitrary string to be placed in a text field upon every button click (*). The problem I am facing is how to inform a text field that such an event occurred?

I have attempted to publish a custom message upon every button click, but my text field does not seem to react to such message at all, even though I have configured it using listenTo.

Here is a (non-)working minimal example describing my unsuccessful struggle so far:

import swing._
import swing.event._

case class SomethingHappened extends Event {
  println("Yes, something indeed has been published!")
}

class MyDialog extends Dialog {
  contents = new BoxPanel(Orientation.Vertical) {
    val myButton = Button("Click me and something will happen!") {
      publish(SomethingHappened())
    }
    contents += new TextField {
      listenTo(myButton)
      reactions += {
        case SomethingHappened() =>
          // This actually never happens... :(
          peer.setText("Voilà!")
          println("You didn't expect it coming, did you?")
      }
    }
    contents += myButton
  }
  open()
}

new MyDialog()

A helping hand would be very much appreciated here. Thanks!

(*) A "button click" is a placeholder for a more complex event and is used here only for simplification purpose (given that, ButtonClicked is not what I am looking for, I need to define and publish a truly custom event). On the other hand updating text field contents is still a desired outcome of that "click".


Solution

  • Try to publish on myButton:

    val myButton: Button = Button("Click me and something will happen!") {
      println(this)
      myButton.publish(SomethingHappened())
    }
    

    this in that case refers to the BoxPanel: The block is not a method of the Button class, it is passed as an argument to it.