swingeventsgroovyswingbuilder

Groovy swingbuilder events for textField


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?


Solution

  • You can do that leveraging closure coercion. Just a quick example to demonstrate:

    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"})
        }
    }