2011-07-04 15 views
6

我正在用scala swing創建一個具有SimpleSwingApplication特性的GUI。 我想要做的是提供一種關閉機制,要求用戶(是,否,取消)如果他還沒有保存文檔。如果用戶點擊取消,Application不應該關閉。但是,我迄今爲止所嘗試的所有內容都未能正常工作,如MainFrame.closecloseOperation如何中斷scala swing中的窗口關閉機制

那麼Scala Swing如何做到這一點呢?

我在斯卡拉2.9。

在此先感謝。

回答

5

略有不同變化有機會定義在scala幀接收到WindowEvent.WINDOW_CLOSING事件時應該做什麼。當一個scala幀接收到一個WINDOW_CLOSING事件時,它會通過調用closeOperation作出反應。因此,要在用戶嘗試關閉幀時顯示對話框,就可以覆蓋closeOperation並實現所需的行爲。

+0

謝謝。在取消棄用後,這個技巧就完成了。 – man

+0

很高興幫助! –

1

我並不真正熟悉斯卡拉擺動,但我發現這個代碼在我的一些舊的測試程序:從什麼霍華德建議

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 _ =>() 
     } 
    } 
    } 
} 

使用DO_NOTHING_ON_CLOSE

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) 
     } 
    } 
    } 
} 
+0

我不知道:是'sys.exit(0)'正常嗎?乍一看似乎太重了,但我可能是錯的。 – Suma

3

這個什麼:

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 
    } 
    } 
} 
+0

不幸的是,這不起作用(至少不是當它是MainFrame時),因爲確認對話框僅在主窗口已經消失後出現。 – sambe

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() 
    } 
}