Java Reference
In-Depth Information
It's not an ideal arrangement, but we will improve on it.
How It Works
The shaded code is of interest - the rest we have seen before. The first block creates the left column of
radio buttons providing a color choice. A
Box
object with a vertical orientation is used to contain the
radio buttons. If you tried the radio buttons you will have found that only one of them can ever be
selected. This is the effect of the
ButtonGroup
object that is used - to ensure radio buttons operate
properly, you must add them to a
ButtonGroup
object.
The
ButtonGroup
object ensures that only one of the radio buttons it contains can be selected at any
one time. Note that a
ButtonGroup
object is not a component - it's just a logical grouping of radio
buttons - so you can't add it to a container. We must still independently add the buttons to the
Box
container that manages their physical arrangement. The
Box
object for the right-hand group of
JCheckBox
objects works in the same way as that for the radio buttons.
Both the
Box
objects holding the columns are added to another
Box
object that implements a horizontal
arrangement to position them side-by-side. Note how the vertical
Box
objects adjust their width to
match that of the largest component in the column. That's why the two columns are bunched towards
the left side. We will see how to improve on this in a moment.
We use a
JPanel
object to hold the buttons. This has a flow layout manager by default, which suits us
here. Calling the
setPreferredSize()
method for each button sets the preferred width and height
to that specified by the
Dimension
object,
size
. This ensures that, space permitting, each button will
be 80 pixels wide and 20 pixels high.
We have introduced another way of obtaining a border for a component here. The
BorderFactory
class (defined in the
javax.swing
package) contains static methods that return standard borders of
various kinds. The
createBevelBorder()
method returns a reference to a
BevelBorder
object as
type
Border
-
Border
being an interface that all border objects implement. We use this border for
each of the buttons. We will try some more of the methods in the
BorderFactory
class later.