我可以创建没有“扩展”的GUI

时间:2013-06-30 09:48:42

标签: scala scala-swing

我开始学习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(...)”。

1 个答案:

答案 0 :(得分:2)

swing应用程序特性给你的两件事。 (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()`
  }
}

请注意,Scala-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")
      }
    }
相关问题