1

I have the following Code:

textField(id: 'programfilter', actionPerformed: { println("execute some action") })

However, the actionPerformed-closure is only called when the textField has the focus and enter is pressed. What do I have to do so that the closure is called on different events e.g. clicking into the textField, selecting text in it or simply on every update of its text?

4

1 回答 1

4

你可以利用闭包强制来做到这一点。只是一个简单的例子来演示:

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"})
    }
}
于 2015-07-06T18:18:13.007 回答