Java Reference
In-Depth Information
How It Works
This code is quite simple. The text to be displayed in the color pane is selected in the series of
if
-
else
statements. They each compare the color passed as an argument with the standard colors we use in
Sketcher and set the
text
variable accordingly. The last
else
should never be reached at the moment,
but it will be obvious if it is. This provides the possibility of adding more flexibility in the drawing color
later on. Note that we also set the foreground color to the currently selected element color, so the text
will be drawn in the color to which it refers.
The type pane uses a
switch
as it is more convenient but the basic process is the same as for the color
pane. If something goes wrong somewhere that results in an invalid element type, the program will
assert through the default case.
All we need now is to implement the status bar in the
SketchFrame
class. For this we must add a data
member to the class that defines the status bar, add the status bar to the content pane of the window in
the class constructor, and extend the
actionPerformed()
methods in the
TypeAction
and
ColorAction
classes to update the status bar when the element type or color is altered.
Try It Out - The Status Bar in Action
You can add the following statement to the
SketchFrame
class to define the status bar as a data
member, following the members defining the menu bar and toolbar:
private StatusBar statusBar = new StatusBar(); // Window status bar
We create
statusBar
as a data member so that it can be accessed throughout the class definition,
including from within the
Action
classes. You need to add one statement to the end of the
SketchFrame
class constructor:
public SketchFrame(String title, Sketcher theApp) {
// Constructor code as before...
getContentPane().add(statusBar, BorderLayout.SOUTH); // Add the statusbar
}
This adds the status bar to the bottom of the application window. To update the status bar when the
element type changes, you can add one statement to the
actionPerformed()
method in the inner
class,
TypeAction
:
public void actionPerformed(ActionEvent e) {
elementType = typeID;
statusBar.setTypePane(typeID);
}
The type pane is updated by calling the
setTypePane()
method for the status bar and passing the
current element type to it as an argument. We can add a similar statement to the
actionPerformed()
method to update the color pane:
public void actionPerformed(ActionEvent e) {
elementColor = color;
statusBar.setColorPane(color);
}