Groovy textField 的 swingbuilder 事件
Groovy swingbuilder events for textField
我有以下代码:
textField(id: 'programfilter', actionPerformed: { println("execute some action") })
但是,actionPerformed 闭包仅在 textField 具有焦点并按下 enter 时调用。我必须做什么才能在不同的事件上调用闭包,例如单击文本字段,选择其中的文本或仅在每次更新其文本时选择文本?
您可以利用 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"})
}
}
我有以下代码:
textField(id: 'programfilter', actionPerformed: { println("execute some action") })
但是,actionPerformed 闭包仅在 textField 具有焦点并按下 enter 时调用。我必须做什么才能在不同的事件上调用闭包,例如单击文本字段,选择其中的文本或仅在每次更新其文本时选择文本?
您可以利用 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"})
}
}