在Groovy 1.6.0 BETA 1中引入了@Bindable這一新的Annotation,該Annotation在Swing編程中使用起來尤為方便,下面給出一個實例供大家參考。其內部的實現原理應該是基于Observer模式的。
點擊‘update’按鈕,隨機更新label的值。請注意,我們僅僅設置了myBean的屬性prop的值,未對label進行任何的顯式操作(比如setText)
import?groovy.beans.Bindable
import?groovy.swing.*
import?javax.swing.*
import?java.awt.*
class?MyBean?{
????@Bindable?
????String?prop
}
def?rand?=?new?Random()
def?greetings?=?['hello,?world',?'hello,?Groovy',?'hello,?山風小子']
def?myBean?=?new?MyBean(prop:greetings[2])
def?swing?=?new?SwingBuilder()
def?frame?=?swing.frame(title:'Bindable?Demo',?location:?[100,?100],?size:[300,?100])?{
????panel(layout:?new?GridLayout(1,?2))?{
????????label(text:bind(source:myBean,?sourceProperty:'prop'))
????????button(action(name:'update',?closure:?{myBean.prop?=?greetings[rand.nextInt(3)]}))
????}
}
frame.setVisible(true)
附:
朝花夕拾——Groovy & Grails
posted on 2008-05-03 16:35
山風小子 閱讀(2734)
評論(3) 編輯 收藏 所屬分類:
Groovy & Grails