Sunday, 12 February 2012

SwingBuilder Series: Layouts - CardLayout

CardLayout is a nice layout to do things like simple step-by-step wizards. Here I've added 3 different panels to a CardLayout, and thanks to two buttons "previous" and "next" I'm going to be able to show them like if I were going through a wizard form.

import static org.fife.ui.rsyntaxtextarea.SyntaxConstants.*
import static java.awt.BorderLayout.*
import static javax.swing.JSplitPane.*
import static javax.swing.JLabel.*
import java.awt.Color
import java.awt.Dimension
import groovy.beans.*

@Bindableclass Step{
def current = 0
}

def step = new Step()
def panelColors = ['RED','YELLOW','BLUE']

panel{
borderLayout() panel(id:'cards',constraints:CENTER){
cardLayout()
panelColors.each{color->
label(
text:color,
horizontalAlignment: CENTER_ALIGNMENT,
opaque:true,
background: Color."${color}" ,
constraints: color
) }
}
hbox(constraints:SOUTH){
button(
id:'previous',
text:'Previous',
enabled:bind{step.current > 0},
actionPerformed:{
step.current--
cards?.layout?.show(cards,colors[step.current])
}
)
button(
id:'next',
text:'Next',
enabled:bind{step.current < 2},
actionPerformed:{
step.current++
cards?.layout?.show(cards,colors[step.current])
}
)
}
}


It's a pretty simple example that looks like this in SwingPad:


Most important to pay attention to are:

  • The name of the constraint of each panel added to CardLayout. That name will be used to show the given panel



panelColors.each{color->
label(
text:color,
horizontalAlignment: CENTER_ALIGNMENT,
opaque:true,
background: Color."${color}" ,
constraints: color
)
}




  • Once we recover the name of the panel we want to show up, we should invoke the CardLayout's show(id) method.




actionPerformed:{
step.current--
cards?.layout?.show(cards,colors[step.current])
}





Here I've used the bind() node to enabling buttons depending on the position of the wizard's current step.

No comments:

Post a Comment