Search code examples
scalaactionscala-swing

Closing a Scala swing frame


I am having a problem closing my Scala swing frame. Here is the code for my exit button

val buttonExit = new Button {
  text = "Exit"
  action = Action("Exit") {
    WorldActor.run(false)
    closer
  }
}

The closer function is defined as:

def closer (){
  top.close
}

where top is the MainFrame. Everytime I try to close, it just suspends and stops responding.


Solution

  • It seems like you can call

    dispose() 
    

    on the Frame.

    dispose is implemented on scala.swing.Window so applies to Frames and Dialogs.

    Calling dispose closes (in a recoverable way, using pack and visible = true to re-open) additional Frames and terminates the application, if called on the last Frame.

    To terminate the app on any Frame call quit() which calls any shutdown code provided before calling System.exit.

    Here's a quick hack to illustrate

    import swing._
    
    object SwingThing extends SimpleSwingApplication {
      def top = new MainFrame {frame =>
        val sf = new Frame {secondFrame =>
          title   = "Secondary Frame"
          visible = true
          contents = new FlowPanel {
            contents += new Button(Action("Close Me") {secondFrame.dispose()})
            contents += new Button(Action("Exit")     {quit()})
          }
        }
        val recoverBtn = new Button(Action("Recover")  {sf.pack(); sf.visible = true})
        val closeBtn   = new Button(Action("Close Me") {frame.dispose()})
        val exitBtn    = new Button(Action("Exit")     {quit()})
    
        contents = new FlowPanel {
          contents += recoverBtn
          contents += closeBtn
          contents += exitBtn
        }
      }
    }