Java Reference
In-Depth Information
Nothing complicated about it. The last
JLabel
(“Monkey wrench in works”) is commented
out because, as noted, the
LayoutManager
throws an exception if the number of components
is not evenly divisible by the number of columns. It was put in during testing and then com-
mented out, but was left in place for further consideration. Note that this layout operates cor-
rectly with more than two columns, but it does assume that all columns are approximately
the same height (relaxing this requirement has been left as an exercise for the reader).
Finally, let's look at the code for the layout manager itself, shown in
Example 14-13
.
After
some constants and fields and two constructors, the methods are listed in about the same or-
der as the discussion earlier in this recipe: the dummy add/remove component methods; then
the
preferredSize()
and
minimumLayoutSize()
methods (which delegate to
com-
puteLayoutSize
); and, finally,
layoutContainer
, which does the actual laying out of the
components within the container. As you can see, the entire
EntryLayout
layout manager
class is only about 140 lines, including a lot of comments.
Example 14-13. EntryLayout.java
// package com.darwinsys.swingui.layout;
public
public class
implements
LayoutManager
{
/** The array of widths, as decimal fractions (0.4 == 40%, etc.). */
protected
class
EntryLayout
EntryLayout
implements
protected final
final
double
double
[]
widthPercentages
;
/** The number of columns. */
protected
protected final
final
int
int
COLUMNS
;
/** The default padding */
protected
protected final
int
HPAD
=
5
,
VPAD
=
5
;
/** The actual padding */
protected
final static
static
int
protected final
final
int
int
hpad
,
vpad
;
/** True if the list of widths was valid. */
protected
protected
boolean
boolean
validWidths
=
false
false
;
/** Construct an EntryLayout with widths and padding specified.
* @param relWidths Array of doubles specifying relative column widths.
* @param h Horizontal padding between items
* @param v Vertical padding between items
*/
public
public
EntryLayout
(
double
double
[]
relWidths
,
int
int
h
,
int
int
v
) {
COLUMNS
=
relWidths
.
length
;
widthPercentages
=
new
new
double
double
[
COLUMNS
];
for
for
(
int
int
i
=
0
;
i
<
relWidths
.
length
;
i
++) {
iif
(
relWidths
[
i
] >=
1.0
)
throw
throw new
new
IllegalArgumentException
(