Scala/Swing:listenTo BoxPanel范围内刚创建的按钮不起作用?

Scala/Swing:listenTo BoxPanel范围内刚创建的按钮不起作用?,swing,scala,subscribe,Swing,Scala,Subscribe,我正在构建一个按钮数量和配置可变的应用程序,应用程序需要监听按钮点击事件,并对其进行处理 由于需要可变数量的按钮和配置,我觉得我必须在框面板范围内为刚刚动态创建的按钮调用listenTo。但我发现按钮的事件不会被接收 但是,如果我记得一个已创建的按钮,并在BoxPanel的范围之外调用listenTo,则会收到它的事件 我想知道为什么listenTo不在BoxPanel的范围内工作是怎么回事?无论如何,我没有看到这种用法的任何编译器错误 下面是我的示例代码: import scala.swing

我正在构建一个按钮数量和配置可变的应用程序,应用程序需要监听按钮点击事件,并对其进行处理

由于需要可变数量的按钮和配置,我觉得我必须在
框面板
范围内为刚刚动态创建的按钮调用
listenTo
。但我发现按钮的事件不会被接收

但是,如果我记得一个已创建的按钮,并在
BoxPanel
的范围之外调用
listenTo
,则会收到它的事件

我想知道为什么
listenTo
不在BoxPanel的范围内工作是怎么回事?无论如何,我没有看到这种用法的任何编译器错误

下面是我的示例代码:

import scala.swing._
import scala.swing.event._

object TouchSelectUI extends SimpleSwingApplication {
  val touchMap = Vector(
    Vector("a", "b", "c"),
    Vector("d", "e", "g")
    // more may be defined in the future
  )
  val keyDemension = new Dimension(40, 25)
  def top = new MainFrame {
    title = "Touch Select Experiment"
    val input = new TextArea {
      columns = 80
      text = ""
    }
    var aButtonRemebered = new Button()
    contents = new FlowPanel {
      require(touchMap.size > 0, {println("The touch key definition is empty!")})
      for (c <- 0 until touchMap(0).size) {
    contents += new BoxPanel(Orientation.Vertical) {
      for (r <- 0 until touchMap.size) {
        val key = new Button {
        text = touchMap(r)(c)
          }
        contents += key
        aButtonRemebered = key
        listenTo(key) // listenTo here does not work.
      }
    }
      }
    contents += input 
    }

    //listenTo(aButtonRemebered) // Here listTo would work to deliver the event to the following reaction!
    reactions += {
      case ButtonClicked(b) => {
    println(s"Button clicked!")
    val c = b.text
    input.text = input.text + c
      }
    }
  }
}
导入scala.swing_
导入scala.swing.event_
对象TouchSelectUI扩展了SimpleSwing应用程序{
val touchMap=向量(
向量(“a”、“b”、“c”),
向量(“d”、“e”、“g”)
//将来可能会定义更多
)
val键尺寸=新尺寸(40,25)
def top=新主机{
title=“触摸选择实验”
val输入=新文本区域{
列=80
text=“”
}
var aButtonRemebered=新建按钮()
内容=新流程面板{
require(touchMap.size>0,{println(“触摸键定义为空!”)})
对于(c这就是你的意思吗

object TouchSelectUI extends SimpleSwingApplication {

  //..

  def top = new MainFrame {

    val main = this

    //..

    contents = new FlowPanel {
      //..
      for (c <- 0 until touchMap(0).size) {
        contents += new BoxPanel(Orientation.Vertical) {
          for (r <- 0 until touchMap.size) {
            val key = new Button
            //..
            main listenTo key
          }
        }
      }
    }
  }
}
您也可以这样做:

  def top = new MainFrame { main =>
他还提供了以下链接:


谢谢!使用“val main=this”和“main listenTo键”缺少。这可能导致在BoxPanel范围内注册,但反应仍在FlowPanel范围内定义。这可能导致响应失败。再次感谢@EECOLOR的及时帮助!@YuShen我没有尝试过,但我认为自别名应该可以。在上面,只需替换
val main=This
使用
main=>
。例如,请看,是的,这是一个好主意!
  def top = new MainFrame { main =>