2012-11-16 36 views
0

如何在scala中的單選按鈕上收聽事件?我有以下代碼,但由於某種原因,反應沒有執行。這是一個對話框,我期待收聽單選按鈕選擇,並相應地更改對話窗口的標題。在Scala Swing中收聽RadioButton上的事件

val dirFileSelector = { 
    List(
    new RadioButton("Directory"){ 
     name = "dir" 

    }, 
    new RadioButton("File"){ 
     name = "file" 
    } 
) 
} 

val buttonGroup = new ButtonGroup 
dirFileSelector map { button=> 
    listenTo(button) 
    buttonGroup.buttons.add(button) 
} 

contents = new BorderPanel{ 

    add(new BoxPanel(Orientation.Horizontal) {contents ++= dirFileSelector}, BorderPanel.Position.North) 
} 

reactions += { 
    case SelectionChanged(buttonSelect) => { 
    println("buttonSelect selection changed") 
    buttonSelect.name match { 
     case "dir" => title = "Add Directory" 
     case "file" => title = "Add File" 
    } 
    } 

} 

回答

2

據我所知,RadioButtons不會發出SelectionChanged事件。但他們確實發出ButtonClicked

這是一個簡單的工作示例得到你想要的效果:

import swing._ 
import swing.event._ 

object app extends SimpleSwingApplication { 
    val dirFileSelector = List(
    new RadioButton() { 
     name = "dir" 
     text = "Directory" 

    }, 
    new RadioButton() { 
     name = "file" 
     text = "File" 
    } 
) 

    new ButtonGroup(dirFileSelector: _*) 

    def top = new MainFrame { 
    title = "Test" 
    contents = new BoxPanel(Orientation.Horizontal) { 
     contents ++= dirFileSelector 
    } 
    dirFileSelector.foreach(listenTo(_)) 
    reactions += { 
     case ButtonClicked(button) => { 
     button.name match { 
      case "dir" => title = "Add Directory" 
      case "file" => title = "Add File" 
     } 
     } 
    } 
    } 
} 
+0

感謝的是,和有關添加一次全部的見解。 –