How to interrupt the window closing mechanism in scala swing

I am creating a GUI with the SimpleSwingApplication in scala swing. I want to make a closing mechanism that asks the user (yes, no, cancel) if he has not already saved the document. If the user clicks Cancel, Application should not be closed. But everything I tried so far with MainFrame.close and closeOperation does not work.

So how is this done in scala swing?

I am on scala 2.9.

Thanks in advance.

+6
source share
4 answers

A bit different than 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 _ => () } } } } 

Using DO_NOTHING_ON_CLOSE , you are given the opportunity to determine what should be done if the WindowEvent.WINDOW_CLOSING event WindowEvent.WINDOW_CLOSING received by a scala frame. When a scala frame receives a WINDOW_CLOSING event, it responds by calling closeOperation . Therefore, to display the dialog when the user tries to close the frame, it is enough to redefine closeOperation and implement the desired behavior.

+5
source

How 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 } } } 
+3
source

I am not very familiar with scala swing, but I found this code in some of my old test programs:

 object GUI extends SimpleGUIApplication { def top = new Frame { title="Test" peer.setDefaultCloseOperation(0) reactions += { case WindowClosing(_) => { println("Closing it?") val r = JOptionPane.showConfirmDialog(null, "Exit?") if (r == 0) sys.exit(0) } } } } 
+1
source

It does what I wanted to do; calling super.closeOperation did not close the frame. I would just say it in a comment, but I'm not allowed yet.

 object FrameCloseStarter extends App { val mainWindow = new MainWindow() mainWindow.main(args) } class MainWindow extends SimpleSwingApplication { def top = new MainFrame { title = "MainFrame" preferredSize = new Dimension(500, 500) pack() open() def frame = new Frame { title = "Frame" preferredSize = new Dimension(500, 500) location = new Point(500,500) pack() peer.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE) override def closeOperation() = { println("Closing") if (Dialog.showConfirmation(message = "exit?") == Result.Ok) { peer.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE) close() } } } frame.open() } } 
0
source

Source: https://habr.com/ru/post/891965/


All Articles