Search code examples
bindinggroovyswingbuilder

Groovy SwingBuilder bind to multiple properties


Is there a way to bind a properties to multiple properties of another object using the SwingBuilder? For example, I want to bind a button's enabled property to two text fields - the button is only enabled when both text fields are non empty.


Solution

  • You can do this sort of thing:

    import groovy.beans.Bindable
    import groovy.swing.SwingBuilder
    import javax.swing.WindowConstants as WC
    
    class CombinedModel {
      @Bindable String text1
      @Bindable String text2
    }
    
    def model = new CombinedModel()
    
    SwingBuilder.build() {
        frame(title:'Multiple Bind Test', pack:true, visible: true, defaultCloseOperation:WC.EXIT_ON_CLOSE ) {
            gridLayout(cols: 2, rows: 0)
    
            label 'Input text 1: '
            textField( columns:10, id:'fielda' )
    
            label 'Input text 2: '
            textField( columns:10, id:'fieldb' )
    
            // Bind our two textFields to our model
            bean( model, text1: bind{ fielda.text } )
            bean( model, text2: bind{ fieldb.text } )
    
            label 'Button: '
            button( text:'Button', enabled: bind { model.text1 && model.text2 } )
        }
    }
    

    As you can see, that binds two textfields to fields in our model, then binds enabled for the button to be true if both text1 and text2 are non-empty