Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to interrupt the window closing mechanism in scala swing

I'm building a GUI with the SimpleSwingApplication trait in scala swing. What I want to do is to provide a mechanism on close, that asks the user (Yes,No,Cancel) if he didn't save the document yet. If the user hits Cancel the Application shouldn't close. But everything I tried so far with MainFrame.close and closeOperation didn't work.

So how is this done in Scala Swing?

I'm on Scala 2.9.

Thanks in advance.

like image 461
Felix Dietze Avatar asked Jul 04 '11 14:07

Felix Dietze


2 Answers

Slightly different variation from what Howard suggested

import scala.swing._

object GUI extends SimpleGUIApplication {
  def top = new Frame {
    title="Test"

    import javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE
    peer.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE)

    override def closeOperation() { showCloseDialog() }

    private def showCloseDialog() {
      Dialog.showConfirmation(parent = null,
        title = "Exit",
        message = "Are you sure you want to quit?"
      ) match {
        case Dialog.Result.Ok => exit(0)
        case _ => ()
      }
    }
  }
}

By using DO_NOTHING_ON_CLOSE you are given a chance to define what should be done when a WindowEvent.WINDOW_CLOSING event is received by the scala frame. When a scala frame receives a WINDOW_CLOSING event it reacts by calling closeOperation. Hence, to display a dialog when the user attempts to close the frame it is enough to override closeOperation and implement the desired behavior.

like image 136
Mirco Dotta Avatar answered Oct 03 '22 23:10

Mirco Dotta


What about this:

import swing._
import Dialog._

object Test extends SimpleSwingApplication { 
  def top = new MainFrame { 
    contents = new Button("Hi")

    override def closeOperation { 
      visible = true
      if(showConfirmation(message = "exit?") == Result.Ok) super.closeOperation  
    }
  }
}
like image 34
gerferra Avatar answered Oct 04 '22 00:10

gerferra