Search code examples
swingscalascala-swing

SimpleSwingApplication created a seemingly infinite amount of identical windows


So I have the following simple program in scala:

object CViewerMainWindow extends SimpleSwingApplication {
    var i = 0
    def top = new MainFrame {
        title = "Hello, World!"
        preferredSize = new Dimension(320, 240)
        // maximize
        visible = true
        contents = new Label("Here is the contents!")
        listenTo(top)
        reactions += {
            case UIElementResized(source) => println(source.size)

    }
}

.

object CViewer {
  def main(args: Array[String]): Unit = {
    val coreWindow = CViewerMainWindow
    coreWindow.top
  }
}

I had hoped it would create a plain window. Instead I get this:

enter image description here


Solution

  • You are creating an infinite loop:

    def top = new MainFrame {
      listenTo(top)
    }
    

    That is, top is calling top is calling top... The following should work:

    def top = new MainFrame {
      listenTo(this)
    }
    

    But a better and safer approach is to forbid that the main frame is instantiated more than once:

    lazy val top = new MainFrame {
      listenTo(this)
    }