package common.components.form; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.ArrayList; import java.util.List; import javax.swing.Box; import javax.swing.JPanel; /** * * Form class is used to create a nicely formatted * form. All labels are right aligned and all components are left * aligned with a gap between the two. * * @author Daniel */ public class Form { private Color color = null; private List components = new ArrayList(); private JPanel form = new JPanel(); private int verticalSpacing = 10; private int horizontalSpacing = 20; /** * Empty constructor for a form */ public Form() { } /** * Called when adding a form component. All components need to be added in * the order in which they will be displayed. * * @param toAdd a FormComponent to be added to the form */ public void add(FormComponent toAdd) { components.add(toAdd); } /** * Called to build the actual form * * @return The built form as VerticalBox to be added to any panel or frame */ public JPanel build() { form.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); //Add each of the labels and the components for(FormComponent item : components) { if(item.getVertLayout() == true) { c.gridwidth = 3; c.gridx = 0; c.weightx = 1; c.fill = GridBagConstraints.HORIZONTAL; c.anchor = GridBagConstraints.NORTHWEST; form.add(item.getLabel(), c); c.gridwidth = 3; c.gridx = 0; c.weightx = 1; c.anchor = GridBagConstraints.NORTHWEST; c.fill = GridBagConstraints.HORIZONTAL; form.add(item.getField(), c); } else { Box labelBox = Box.createVerticalBox(); labelBox.add(item.getLabel()); labelBox.add(Box.createVerticalStrut(verticalSpacing)); //Add the components c.gridwidth = 1; c.weightx = 1; c.gridx = 0; c.anchor = GridBagConstraints.NORTHEAST; form.add(labelBox, c); c.weightx = 1; c.gridx = 1; form.add(Box.createHorizontalStrut(horizontalSpacing), c); Box componentBox = Box.createVerticalBox(); componentBox.add(item.getField()); componentBox.add(Box.createVerticalStrut(verticalSpacing)); c.weightx = 1; c.gridx = 2; c.anchor = GridBagConstraints.NORTHWEST; form.add(componentBox, c); } } if(color != null) { form.setBackground(color); } form.setVisible(true); return form; } /** * Sets the color of the background of * the JPanel that is returned * * @param color */ public void setColor(Color color) { this.color = color; } /** * If you ever wanted to get the color for whatever reason * * @return */ public Color getColor() { return this.color; } /** * Set the horizontal spacing distance between the two columns * * @param spacing */ public void setHorizontalSpacing(int spacing) { this.horizontalSpacing = spacing; } /** * Set the vertical spacing distance between the components and labels * * @param spacing */ public void setVerticalSpacing(int spacing) { this.verticalSpacing = spacing; } }