public class TableLayout extends java.lang.Object implements java.awt.LayoutManager2, java.io.Serializable, TableLayoutConstants
TableLayout is a layout manager that is more powerful than GridBagLayout yet much easier to use.
BackgroundTableLayout is a layout manager that arranges components in rows and columns like a spreadsheet. TableLayout allows each row or column to be a different size. A row or column can be given an absolute size in pixels, a percentage of the available space, or it can grow and shrink to fill the remaining space after other rows and columns have been resized.
Using spreadsheet terminology, a cell is the intersection of a row and column. Cells have finite, non-negative sizes measured in pixels. The dimensions of a cell depend solely upon the dimensions of its row and column.
A component occupies a rectangular group of one or more cells. The component can be aligned within those cells using four vertical and six horizontal justifications. The vertical justifications are left, center, right, and full. The horizontal justifications are left, center, right, full, leading, and trailing. With full justification the component is stretched either vertically or horizontally to fit the cell or group of cells.
Justification
Leading and trailing justification are used to support languages that are read from right to left. See the
java.awt.ComponentOrientation
class for details and http://java.sun.com/products/jfc/tsc/articles/bidi
for an introduction to component orientation and bidirectional text support. The leading justification will align the
component along the leading edge of the container and the trailing justification will align the component along the
trailing edge. There is no leading or trailing justification along the vertical axis since all modern languages are
read from top to bottom and no bottom-to-top orientation is defined in java.awt.ComponentOrientation.
For components using the ComponentOrientation.LEFT_TO_RIGHT
orientation, the leading edge is the left
edge and the trailing edge is the right one. For components using the ComponentOrientation.RIGHT_TO_LEFT
orientation, the opposite is true. For components that are using ComponentOrientation.UNKNOWN
and for Java runtime environments that do not support component orientation, left-to-right orientation is assumed for
backwards compatibility.
Horizontal and vertical gaps can be placed between rows and columns in two ways. If uniformed gaps are desired, the
setHGap
and
setVGap
methods may be used. To vary the size of gaps, simply use empty rows and columns with absolute sizes.
Similiarly, to make a border around a container that does not have insets, use empty rows and columns along the edges
of the container.
Using TableLayout is a simple two step process. First, create a grid for your container by specifying row and column
sizes using either a TableLayout constructor or the insertRow
and insertColumn
methods.
Second, add components to the cells formed by the rows and columns.
When adding a component to a container that uses TableLayout, you specify the component's constraints that state
which cells the component will occupy and how the component will be aligned. The constraints can be specified into
two ways. The TableLayoutConstraints
class can be used to systematically specify the constraints. This
is useful to dynamic code, bean builders, and rapid application development software.
For manual coding, a quicker and easier way to specify constraints is with a short string in the form "x1, y1, x2, y2, hAlign, vAlign" where (x1, y1) identifies the top left cell (column x1, row y1) for the component and (x2, y2) identfies the bottom right cell. x2 and y2 are optional. If they are not specified, the component will occupy only one cell, (x1, y1). hAlign and vAlign are also optional with default values of full justification. Alignments may be spelt fully as in "LEFT" or abbreviated as in "L". The text is not case sensitive, but it is recommended that uppercase is used for two reasons. First, these text values are in essence constants. Second, some fonts use the same glyphs for representing a lowercase L and the number one. Ex., "l" vs. "1". Even fonts that do not will often use similar glyphs so using uppercase avoids confusion.
Dynamically altering the layoutRows and columns can be dynamically created, resized, and removed at any time, even if the container is visible. Components will be shifted appropriately as rows and columns are inserted or removed, just as cells are shifted in a spreadsheet.
Rows and columns can be made "hidden" or effectively invisible by setting their size to zero. They can be shown again by setting their size back to a non-zero value. This is very useful for toggle form elements without having to remove individual components.
Preferred sizes
Often it is desireable to make a row or column just large enough to ensure that all components contained partially or
wholly in that row or column are their preferred size. To make this easy, there is a constant called
PREFERRED
that can be used to specify row or column sizes. There is another constant called
MINIMUM
that does a similar task using components' minimum sizes instead of their preferred sizes.
There is no corresponding MAXIMUM
constant for several reasons. First, it is mathematically impossible
to honor both the minimum and maximum sizes of more than one component when conflicts arise. For example, say
components a and b are in the same row. If a's maximum height is less than b's minimum height, then one of these
constraints must be violated. Since TableLayout is a complete, general Cartesian layout manager, it would be possible
to specify conflicting constraints if a MAXIMUM
constant existed.
Second, the ability to make a component grow up to a maximum size is primarily of interest to layout managers like
SpringLayout
that have to balance the sizes of components because the presence of one component affects
the size of another. Other than the effect of preferred and minimum size rows/columns, which are essentially
convenient ways of specifying absolute sizes, the existence and constraints of one component does not affect any
other components when using TableLayout. This is accomplished because rows and columns are explicit in TableLayout.
Third, the ability to constrain a component to its maximum size is subsumed by the ability to constrain it to its preferred size, which is precisely what happens when a component is aligned using anything but full justification. In the case of full justification, the component's maximum size is by definition unbounded.
Exampleimport java.awt.*; import javax.swing.*; import info.clearthought.layout.TableLayout;public class Preferred extends JFrame { public static void main (String args[]) { new Preferred(); } public Preferred () { super("The Power of Preferred Sizes"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container pane = getContentPane(); // b - border // f - FILL // p - PREFERRED // vs - vertical space between labels and text fields // vg - vertical gap between form elements // hg - horizontal gap between form elements double b = 10; double f = TableLayout.FILL; double p = TableLayout.PREFERRED; double vs = 5; double vg = 10; double hg = 10; double size[][] = {{b, f, hg, p, hg, p, b}, {b, p, vs, p, vg, p, vs, p, vg, p, vs, p, vg, p, b}}; TableLayout layout = new TableLayout(size); pane.setLayout (layout); // Create all controls JLabel labelName = new JLabel("Name"); JLabel labelAddress = new JLabel("Address"); JLabel labelCity = new JLabel("City"); JLabel labelState = new JLabel("State"); JLabel labelZip = new JLabel("Zip"); JTextField textfieldName = new JTextField(10); JTextField textfieldAddress = new JTextField(20); JTextField textfieldCity = new JTextField(10); JTextField textfieldState = new JTextField(2); JTextField textfieldZip = new JTextField(5); JButton buttonOk = new JButton("OK"); JButton buttonCancel = new JButton("Cancel"); JPanel panelButton = new JPanel(); panelButton.add(buttonOk); panelButton.add(buttonCancel); // Add all controls pane.add(labelName, "1, 1, 5, 1"); pane.add(textfieldName, "1, 3, 5, 3"); pane.add(labelAddress, "1, 5, 5, 5"); pane.add(textfieldAddress, "1, 7, 5, 7"); pane.add(labelCity, "1, 9"); pane.add(textfieldCity, "1, 11"); pane.add(labelState, "3, 9"); pane.add(textfieldState, "3, 11"); pane.add(labelZip, "5, 9"); pane.add(textfieldZip, "5, 11"); pane.add(panelButton, "1, 13, 5, 13"); pack(); setResizable(false); show(); } }
Modifier and Type | Class and Description |
---|---|
static class |
TableLayout.Entry |
Modifier and Type | Field and Description |
---|---|
protected static int |
C
Indicates a column
|
protected static boolean |
checkForComponentOrientationSupport
Used to minimize reflection calls
|
protected int[][] |
crOffset
Offsets of crs in pixels.
|
protected int[][] |
crSize
Sizes of crs in pixels
|
protected double[][] |
crSpec
Sizes of crs expressed in absolute and relative terms
|
protected static double[][] |
defaultSize
Default row/column size
|
protected boolean |
dirty
Indicates whether or not the size of the cells are known for the last known size of the container.
|
protected int |
hGap
Horizontal gap between columns
|
protected java.util.LinkedList<TableLayout.Entry> |
list
List of components and their sizes
|
protected static java.lang.reflect.Method |
methodGetComponentOrientation
Method used to get component orientation while preserving compatability with earlier versions of
java.awt.Container.
|
protected int |
oldHeight
Previous known height of the container
|
protected int |
oldWidth
Previous known width of the container
|
protected static int |
R
Indicates a row
|
protected int |
vGap
Vertical gap between rows
|
Constructor and Description |
---|
TableLayout()
Constructs an instance of TableLayout.
|
TableLayout(double[][] size)
Constructs an instance of TableLayout.
|
TableLayout(double[] col,
double[] row)
Constructs an instance of TableLayout.
|
Modifier and Type | Method and Description |
---|---|
void |
addLayoutComponent(java.awt.Component component,
java.lang.Object constraint)
Adds the specified component with the specified name to the layout.
|
void |
addLayoutComponent(java.lang.String name,
java.awt.Component component)
Adds the specified component with the specified name to the layout.
|
protected int |
assignAbsoluteSize(int z,
int availableSize)
Assigns absolute sizes.
|
protected void |
assignFillSize(int z,
int availableSize)
Assigns FILL sizes.
|
protected int |
assignPrefMinSize(int z,
int availableSize,
double typeOfSize)
Assigned sizes to preferred and minimum size columns and rows.
|
protected int |
assignRelativeSize(int z,
int availableSize)
Assigns relative sizes.
|
protected java.awt.Dimension |
calculateLayoutSize(java.awt.Container container,
double typeOfSize)
Calculates the preferred or minimum size for the methods preferredLayoutSize and minimumLayoutSize.
|
protected int |
calculateLayoutSize(java.awt.Container container,
int z,
double typeOfSize,
TableLayout.Entry[] entryList,
java.awt.Dimension[] prefMinSize)
Calculates the preferred or minimum size for the method calculateLayoutSize(Container container, double
typeOfSize).
|
protected void |
calculateOffset(int z,
java.awt.Insets inset)
Calculates the offset of each cr.
|
protected void |
calculateSize(java.awt.Container container)
Calculates the sizes of the rows and columns based on the absolute and relative sizes specified in
crSpec[R] and crSpec[C] and the size of the container. |
protected int[] |
calculateSizeAndOffset(TableLayout.Entry entry,
int preferredSize,
boolean isColumn)
Calculates the vertical/horizontal offset and size of a component.
|
void |
deleteColumn(int i)
Deletes a column in this layout.
|
protected void |
deleteCr(int z,
int i)
Deletes a cr for the methods deleteRow or deleteColumn.
|
void |
deleteRow(int i)
Deletes a row in this layout.
|
double[] |
getColumn()
Gets the sizes of columns in this layout.
|
double |
getColumn(int i)
Gets the width of a single column in this layout.
|
protected java.awt.ComponentOrientation |
getComponentOrientation(java.awt.Container container)
Gets the container's component orientation.
|
TableLayoutConstraints |
getConstraints(java.awt.Component component)
Gets the constraints of a given component.
|
int |
getHGap()
Gets the horizontal gap between colunns.
|
java.util.List<java.lang.Object> |
getInvalidEntry()
Determines whether or not there are any components with invalid constraints.
|
float |
getLayoutAlignmentX(java.awt.Container parent)
Returns the alignment along the x axis.
|
float |
getLayoutAlignmentY(java.awt.Container parent)
Returns the alignment along the y axis.
|
int |
getNumColumn()
Gets the number of columns in this layout.
|
int |
getNumRow()
Gets the number of rows in this layout.
|
java.util.List<java.lang.Object> |
getOverlappingEntry()
Gets a list of overlapping components and their constraints.
|
double[] |
getRow()
Gets the height of a single row in this layout.
|
double |
getRow(int i)
Gets the sizes of a row in this layout.
|
int |
getVGap()
Gets the vertical gap between rows.
|
protected void |
init(double[] col,
double[] row)
Initializes the TableLayout for all constructors.
|
void |
insertColumn(int i,
double size)
Inserts a column in this layout.
|
void |
insertCr(int z,
int i,
double size)
Inserts a cr for the methods insertRow or insertColumn.
|
void |
insertRow(int i,
double size)
Inserts a row in this layout.
|
void |
invalidateLayout(java.awt.Container target)
Invalidates the layout, indicating that if the layout manager has cached information it should be discarded.
|
void |
layoutContainer(java.awt.Container container)
To lay out the specified container using this layout.
|
java.awt.Dimension |
maximumLayoutSize(java.awt.Container target)
Returns the maximum dimensions for this layout given the components in the specified target container.
|
java.awt.Dimension |
minimumLayoutSize(java.awt.Container container)
Determines the minimum size of the container argument using this layout.
|
java.awt.Dimension |
preferredLayoutSize(java.awt.Container container)
Determines the preferred size of the container argument using this layout.
|
void |
removeLayoutComponent(java.awt.Component component)
Removes the specified component from the layout.
|
void |
setColumn(double[] column)
Adjusts the number and sizes of rows in this layout.
|
void |
setColumn(int i,
double size)
Adjusts the width of a single column in this layout.
|
void |
setConstraints(java.awt.Component component,
TableLayoutConstraints constraint)
Sets the constraints of a given component.
|
protected void |
setCr(int z,
double[] size)
Sets the sizes of rows or columns for the methods setRow or setColumn.
|
protected void |
setCr(int z,
int i,
double size)
Sets the sizes of rows or columns for the methods setRow or setColumn.
|
void |
setHGap(int hGap)
Sets the horizontal gap between colunns.
|
void |
setRow(double[] row)
Adjusts the number and sizes of rows in this layout.
|
void |
setRow(int i,
double size)
Adjusts the height of a single row in this layout.
|
void |
setVGap(int vGap)
Sets the vertical gap between rows.
|
java.lang.String |
toString()
Converts this TableLayout to a string.
|
protected static final double[][] defaultSize
protected static final int C
protected static final int R
protected static boolean checkForComponentOrientationSupport
protected static java.lang.reflect.Method methodGetComponentOrientation
protected double[][] crSpec
protected int[][] crSize
protected int[][] crOffset
protected java.util.LinkedList<TableLayout.Entry> list
protected boolean dirty
protected int oldWidth
protected int oldHeight
protected int hGap
protected int vGap
public TableLayout()
public TableLayout(double[][] size)
size
- widths of columns and heights of rows in the format, {{col0, col1, col2, ..., colN}, {row0, row1,
row2, ..., rowM}} If this parameter is invalid, the TableLayout will have exactly one row and one
column.public TableLayout(double[] col, double[] row)
col
- widths of columns in the format, {{col0, col1, col2, ..., colN}row
- heights of rows in the format, {{row0, row1, row2, ..., rowN}protected void init(double[] col, double[] row)
col
- widths of columns in the format, {{col0, col1, col2, ..., colN}row
- heights of rows in the format, {{row0, row1, row2, ..., rowN}public TableLayoutConstraints getConstraints(java.awt.Component component)
component
- desired componentpublic void setConstraints(java.awt.Component component, TableLayoutConstraints constraint)
component
- desired component. This parameter cannot be null.constraint
- new set of constraints. This parameter cannot be null.public void setColumn(double[] column)
layout.layoutContainer(container); container.repaint();or
window.pack()If this is not done, the changes in the layout will not be seen until the container is resized.
column
- widths of each of the columnsgetColumn()
public void setRow(double[] row)
layout.layoutContainer(container);
container.repaint();
or
window.pack()If this is not done, the changes in the layout will not be seen until the container is resized.
row
- heights of each of the rows. This parameter cannot be null.getRow()
protected void setCr(int z, double[] size)
z
- indicates row or columnsize
- new cr sizepublic void setColumn(int i, double size)
layout.layoutContainer(container);
container.repaint();
or
window.pack()If this is not done, the changes in the layout will not be seen until the container is resized.
i
- zero-based index of column to set. If this parameter is not valid, an ArrayOutOfBoundsException will be
thrown.size
- width of the column. This parameter cannot be null.getColumn()
public void setRow(int i, double size)
layout.layoutContainer(container);
container.repaint();
or
window.pack()If this is not done, the changes in the layout will not be seen until the container is resized.
i
- zero-based index of row to set. If this parameter is not valid, an ArrayOutOfBoundsException will be
thrown.size
- height of the row. This parameter cannot be null.getRow()
protected void setCr(int z, int i, double size)
z
- indicates row or columni
- indicates which cr to resizesize
- new cr sizepublic double[] getColumn()
setColumn(double[])
public double[] getRow()
setRow(double[])
public double getColumn(int i)
i
- zero-based index of row to get. If this parameter is not valid, an ArrayOutOfBoundsException will be
thrown.setRow(double[])
public double getRow(int i)
i
- zero-based index of row to get. If this parameter is not valid, an ArrayOutOfBoundsException will be
thrown.setRow(double[])
public int getNumColumn()
public int getNumRow()
public int getHGap()
public int getVGap()
public void setHGap(int hGap)
hGap
- the horizontal gap in pixelspublic void setVGap(int vGap)
vGap
- the horizontal gap in pixelspublic void insertColumn(int i, double size)
setColumn
.i
- zero-based index at which to insert the columnsize
- size of the column to be insertedsetColumn(double[])
,
deleteColumn(int)
public void insertRow(int i, double size)
setRow
.i
- zero-based index at which to insert the rowsize
- size of the row to be insertedsetRow(double[])
,
deleteRow(int)
public void insertCr(int z, int i, double size)
z
- indicates row or columni
- zero-based index at which to insert the crsize
- size of cr being insertedpublic void deleteColumn(int i)
setColumn
.i
- zero-based index of column to deletesetColumn(double[])
,
deleteColumn(int)
public void deleteRow(int i)
setRow
. There must be at least two rows in order
to delete a row.i
- zero-based index of row to deletesetRow(double[])
,
deleteRow(int)
protected void deleteCr(int z, int i)
z
- indicates row or columni
- zero-based index of cr to deletepublic java.lang.String toString()
toString
in class java.lang.Object
public java.util.List<java.lang.Object> getInvalidEntry()
getOverlappingEntry()
public java.util.List<java.lang.Object> getOverlappingEntry()
getInvalidEntry()
protected void calculateSize(java.awt.Container container)
crSpec[R]
and crSpec[C]
and the size of the container. The result is stored in
crSize[R]
and crSize[C]
.container
- container using this TableLayoutprotected int assignAbsoluteSize(int z, int availableSize)
z
- indicates row or columnavailableSize
- amount of space available in the containerprotected int assignRelativeSize(int z, int availableSize)
z
- indicates row or columnavailableSize
- amount of space available in the containerprotected void assignFillSize(int z, int availableSize)
z
- indicates row or columnavailableSize
- amount of space available in the containerprotected void calculateOffset(int z, java.awt.Insets inset)
z
- indicates row or columnprotected int assignPrefMinSize(int z, int availableSize, double typeOfSize)
z
- indicates row or columnavailableSize
- amount of space available in the containertypeOfSize
- indicates preferred or minimumpublic void layoutContainer(java.awt.Container container)
User code should not have to call this method directly.
layoutContainer
in interface java.awt.LayoutManager
container
- container being served by this layout managerprotected java.awt.ComponentOrientation getComponentOrientation(java.awt.Container container)
container
- Container whose orientation is being queriedprotected int[] calculateSizeAndOffset(TableLayout.Entry entry, int preferredSize, boolean isColumn)
entry
- entry containing component and contraintspreferredSize
- previously calculated preferred width/height of componentisColumn
- if true, this method is being called to calculate the offset/size of a column. if false,... of a
row.public java.awt.Dimension preferredLayoutSize(java.awt.Container container)
preferredLayoutSize
in interface java.awt.LayoutManager
container
- container being served by this layout managerpublic java.awt.Dimension minimumLayoutSize(java.awt.Container container)
minimumLayoutSize
in interface java.awt.LayoutManager
container
- container being served by this layout managerprotected java.awt.Dimension calculateLayoutSize(java.awt.Container container, double typeOfSize)
container
- container whose size is being calculatedtypeOfSize
- indicates preferred or minimumprotected int calculateLayoutSize(java.awt.Container container, int z, double typeOfSize, TableLayout.Entry[] entryList, java.awt.Dimension[] prefMinSize)
container
- container whose size is being calculatedz
- indicates row or columntypeOfSize
- indicates preferred or minimumentryList
- list of Entry objectsprefMinSize
- list of preferred or minimum sizespublic void addLayoutComponent(java.lang.String name, java.awt.Component component)
addLayoutComponent
in interface java.awt.LayoutManager
name
- indicates entry's position and anchorcomponent
- component to addpublic void addLayoutComponent(java.awt.Component component, java.lang.Object constraint)
addLayoutComponent
in interface java.awt.LayoutManager2
component
- component to addconstraint
- indicates entry's position and alignmentpublic void removeLayoutComponent(java.awt.Component component)
removeLayoutComponent
in interface java.awt.LayoutManager
component
- component being removedpublic java.awt.Dimension maximumLayoutSize(java.awt.Container target)
maximumLayoutSize
in interface java.awt.LayoutManager2
target
- the component which needs to be laid outpublic float getLayoutAlignmentX(java.awt.Container parent)
getLayoutAlignmentX
in interface java.awt.LayoutManager2
public float getLayoutAlignmentY(java.awt.Container parent)
getLayoutAlignmentY
in interface java.awt.LayoutManager2
public void invalidateLayout(java.awt.Container target)
invalidateLayout
in interface java.awt.LayoutManager2
Copyright © 2004-2014 FEUP-LSTS and Neptus developers. All Rights Reserved.