Search code examples
groovyswingbuilderspringlayout

SpringLayout with SwingBuilder


I am trying to quickly and easily layout rows and columns of buttons and labels. Having buttons and labels be the same width looks ridiculous, so I have ruled out GridLayout. I may slit my wrists if someone suggests GridBagLayout. SO I was thinking SpringLayout was my best option. But I am not a Groovy expert, and that is especially true of GUI stuff.

So I was hoping someone could provide or point to a simple example of using SpringLayout with SwingBuilder. In particular, how to specify constraints, since in all of the SwingBuilder examples I see, each widget instance gets created on the fly without a named instance. So how would I reference another sibling or parent widget for relative constraints? I have not found anything on the internet that can explain this.

Working example code would with 2 rows/2 columns would get the win!


Solution

  • You can set id in a node and refer to the id later as variable, for example:

    import javax.swing.*
    import groovy.swing.*
    
    new SwingBuilder().edt {
    
        def layout = springLayout()
    
        frame(title: 'SpringLayout', visible: true, layout: layout) {
            label(id: 'label1', text: 'Label1: ')
            textField(id: 'textField1', columns: 15)
            label(id: 'label2', text: 'Label2: ')
            textField(id: 'textField2', columns: 15)
        }
    
        def label1Cons = layout.getConstraints(label1)
        label1Cons.setX(Spring.constant(5))
        label1Cons.setY(Spring.constant(5))
        def textField1Cons = layout.getConstraints(textField1)
        textField1Cons.setX(Spring.sum(Spring.constant(5), label1Cons.getConstraint(SpringLayout.EAST)))
        textField1Cons.setY(Spring.constant(5))
    
        def label2Cons = layout.getConstraints(label2)
        label2Cons.setX(Spring.constant(5))
        label2Cons.setY(Spring.sum(Spring.constant(30), label2Cons.getConstraint(SpringLayout.NORTH)))
        def textField2Cons = layout.getConstraints(textField2)
        textField2Cons.setX(Spring.sum(Spring.constant(5), label2Cons.getConstraint(SpringLayout.EAST)))
        textField2Cons.setY(Spring.sum(Spring.constant(25), textField1Cons.getConstraint(SpringLayout.NORTH)))
    
    }
    

    Perhaps you should try MigLayout for an easier solution.