JLabelGroup¶
JLabelGroup is used to create pretty layouted formulas.
Forms usually consist of two colums. In the right column the input fields are located, with their respective labels in the left column. Swing only provides the tedious GridBagLayout for those layouts, though.
JLabelGroup offers an much easier way to create formulas with properly aligned input fields and labels.
/*
* Examples for the jshred library
*
* Copyright (c) 2004 Richard "Shred" Körber
* http://www.shredzone.net/go/jshred
*
* This example is free software. Use and modify it at will.
*/
import net.shredzone.jshred.swing.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
/**
* This example creates two text fields and a combobox, each with a
* JLabelGroup before it. You can see how easy it is to create a well-
* layouted form with JLabelGroup.
*/
public class LabelGroup extends JFrame {
/**
* Create a new LabelGroup example.
*/
public LabelGroup() {
// Create a Box
// I usually arrange all input fields in a Box layout, but this
// is not a requirement for JLabelGroup. You can use any layout
// as long as the components are vertically arranged.
Box box = Box.createVerticalBox();
// Create a JLabelGroup reference
// It will be initialized to null, and will later hold a reference
// to the most recently created JLabelGroup.
JLabelGroup group = null;
// Create a "Name" text field
// As you will see now, the component, a label text and the group
// reference is passed to the JLabelGroup constructor. The returned
// component is the new group reference, and is also added to the
// Box.
JTextField tfName = new JTextField();
group = new JLabelGroup(tfName, "Name:", group);
box.add(group);
// Create a "Type" combo box
// This is similar to the Name text field above. JLabelGroup is not
// limited to text fields, but you can use any (lightweight and
// heavyweight) component.
Object[] types = new Object[] {"Friend", "Relative", "Company"};
JComboBox jcType = new JComboBox(types);
group = new JLabelGroup(jcType, "Contact Type:", group);
box.add(group);
// Create a "Phone" text field
// All the JLabelGroups are chained this way.
JTextField jfPhone = new JTextField();
group = new JLabelGroup(jfPhone, "Phone #:", group);
box.add(group);
// Rearrange the JLabelGroup layout
// If you have added all the components to the JLabelGroup chain,
// this method will find the width of the broadest label, and align
// all the other labels to that width.
group.rearrange();
// If you add or remove components later, just re-invoke the rearrange
// method again, with the last JLabelGroup of the chain.
// Add the box to the frame
getContentPane().add(box, BorderLayout.NORTH);
}
/**
* Start this demo as an application.
*
* @param args Shell arguments
*/
public static void main(String[] args) {
LabelGroup demo = new LabelGroup();
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.pack();
demo.show();
}
}