我正在构建一个具有SimpleSwingApplication
scala swing 特性的 GUI。我想要做的是提供一种关闭机制,询问用户(是,否,取消)他是否还没有保存文档。如果用户点击取消,则Application
不应关闭。但是到目前为止我尝试过的一切都MainFrame.close
没有closeOperation
奏效。
那么这是如何在 Scala Swing 中完成的呢?
我在 Scala 2.9 上。
提前致谢。
我正在构建一个具有SimpleSwingApplication
scala swing 特性的 GUI。我想要做的是提供一种关闭机制,询问用户(是,否,取消)他是否还没有保存文档。如果用户点击取消,则Application
不应关闭。但是到目前为止我尝试过的一切都MainFrame.close
没有closeOperation
奏效。
那么这是如何在 Scala Swing 中完成的呢?
我在 Scala 2.9 上。
提前致谢。
与霍华德建议的略有不同
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 _ => ()
}
}
}
}
通过使用,您有机会定义当scala 框架接收到事件DO_NOTHING_ON_CLOSE
时应该做什么。WindowEvent.WINDOW_CLOSING
当 Scala 框架接收到一个WINDOW_CLOSING
事件时,它会通过调用closeOperation
. 因此,要在用户尝试关闭框架时显示对话框,覆盖closeOperation
并实现所需的行为就足够了。
那这个呢:
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
}
}
}
我对 scala swing 不是很熟悉,但我在一些旧的测试程序中发现了这段代码:
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)
}
}
}
}
这就是我想做的;调用 super.closeOperation 并没有关闭框架。我会在评论中这么说,但我还没有被允许。
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()
}
}