2013-06-30 205 views
2

我開始學習Scala並且感到困惑。我可以在沒有「擴展SimpleSwingApplication」或「SimpleGUIApplication」的情況下創建圖形用戶界面,或者可能還沒有?我試圖這樣做:我可以在沒有「擴展」的情況下創建GUI嗎?

import scala.swing._ 

object Main { 
def main(args:Array[String]): Unit = { 
    val frame = new Frame {title = "test GUI"} 
    val button = new Button {text = "test button"} 
    val uslPanel = new BoxPanel(Orientation.Vertical) { 
     contents += button 
     } 
    //listenTo(button) 

    frame.contents_=(uslPanel) 
    frame.visible_=(true) 
    } 
} 

它的工作原理,但如果只有「listenTo(botton)」被評論。如何在沒有「擴展SimpleGui ...等」的情況下使用「listenTo(...)」。

回答

2

擺動應用程序特性給你的兩件事。 (1)他們將初始代碼推遲到事件調度線程(參見Swing's Threading Policy,還有here)。 (2)他們繼承了Reactor這個特性,它給了你現在缺少的listenTo方法。

我想你應該只是混合在SwingApplication應用程序的特點,這是最簡單的。否則,你可以手工做這些事情:

import scala.swing._ 

object Main { 
    def main(args: Array[String]) { 
    Swing.onEDT(initGUI) // Scala equivalent of Java's SwingUtilities.invokeLater 
    } 

    def initGUI() { 
    val frame = new Frame { title = "test GUI" } 
    val button = new Button { text = "test button" } 
    val uslPanel = new BoxPanel(Orientation.Vertical) { 
     contents += button 
    } 
    val r = new Reactor {} 
    r.listenTo(button) 
    r.reactions += { 
     case event.ButtonClicked(_) => println("Clicked") 
    } 

    frame.contents = uslPanel 
    frame.visible = true // or use `frame.open()` 
    } 
} 

注意,在斯卡拉-Swing中的每個小部件繼承Reactor,所以你經常會發現這種風格:

val button = new Button { 
     text = "test button" 
     listenTo(this) // `listenTo` is defined on Button because Button is a Reactor 
     reactions += { // `reactions` as well 
     case event.ButtonClicked(_) => println("Clicked") 
     } 
    } 
+0

是的,它的作品,非常感謝。 – Bersano

相關問題