我有以下代码:
textField(id: 'programfilter', actionPerformed: { println("execute some action") })
但是,仅当textField具有焦点并按下enter时才会调用actionPerformed-closure。我必须做什么才能在不同的事件上调用闭包,例如单击textField,在其中选择文本或只是在文本的每次更新?
答案 0 :(得分:2)
你可以利用closure coercion来做到这一点。只是一个简单的例子来证明:
import groovy.swing.SwingBuilder
import java.awt.event.*
import javax.swing.event.*
import javax.swing.WindowConstants as WC
SwingBuilder.build() {
frame(title:'Swing Listener example', size:[300,100],
visible:true, defaultCloseOperation:WC.EXIT_ON_CLOSE) {
gridLayout(cols: 2, rows: 0)
label 'Input text: '
input = textField(columns:10, actionPerformed: { echo.text = input.text.toUpperCase() })
label 'Echo: '
echo = label()
input.document.addDocumentListener(
[insertUpdate: { echo.text = input.text },
removeUpdate: { echo.text = input.text },
changedUpdate: { e -> println e }] as DocumentListener)
input.addFocusListener(
[focusGained: { e -> println "Focus gained: $e.cause"},
focusLost: {e -> println "Focus lost: $e.cause"}] as FocusListener)
input.addCaretListener({ e -> println "Caret event: $e"})
}
}