Java Reference
In-Depth Information
setFont(paneFont); // Set the fixed font
setHorizontalAlignment(CENTER); // Center the pane text
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
setPreferredSize(new Dimension(100,20));
setText(text); // Set the text in the pane
}
// Font for pane text
private Font paneFont = new Font("Serif", Font.PLAIN, 10);
}
}
How It Works
Since the
StatusBar
class implements our
Constants
interface, all the variables that represent
possible element types and colors are available. This outline version of
StatusBar
has two data
members of type
StatusPane
, which will be the panes showing the current color and element type.
The initial information to be displayed by a
StatusPane
object is passed to the constructor as a
String
object.
In the
StatusBar
constructor, we update the information to be displayed in each pane by calling the
setColorPane()
and
setTypePane()
methods. These ensure that initially the
StatusPane
objects
display the default color and type that we've defined for the application. One or other of these methods will
be called whenever it is necessary to update the status bar. We'll complete the definitions for
setColorPane()
and
setTypePane()
when we've been through the detail of the
StatusPane
class.
The
StatusBar
panel has a
FlowLayout
manager that is set in the constructor. The panes in the
status bar need only display a small amount of text, so we've derived the
StatusPane
class from the
JLabel
class - so a pane for the status bar will be a specialized kind of
JLabel
. This means that we
can call the
setText()
method that is inherited from
JLabel
to set the text for our
StatusPane
objects. The
StatusPane
objects will be left-justified when they are added to the status bar, as a result
of the first argument to the
setLayout()
method call in the
StatusBar
constructor. The layout
manager will leave a ten-pixel horizontal gap between successive panes in the status bar, and a three-
pixel vertical gap between rows of components. The border for the status bar is a single dark gray line
that we add using the
BorderFactory
method.
The only data member in the
StatusPane
class is the
Font
object,
font
. We've defined the font to
be used for pane text as a standard 10-point Serif. In the constructor we set the background color to
light gray, the foreground color to dark gray, and we set the standard font. We also set the alignment of
the text as centered by calling the inherited method
setHorizontalAlignment()
, and passing the
value
CENTER
to it - this is defined in the base class,
JLabel
.
If we can maintain a fixed width for each pane, it will prevent the size of the pane jumping around when
we change the text. So we've set the
setPreferredSize()
at the minimum necessary for
accommodating our longest text field. Lastly, in the
StatusPane
constructor we set the text for the
pane by calling the inherited
setText()
method.