Java Reference
In-Depth Information
Because we refer to the
File
class here, we need to add an import statement for
java.io.File
to the
beginning of the
SketchFrame.java
source file. This code assumes all icon files follow the convention that
their name is the same as the
String
associated with the
NAME
key. If you want to have any file name, you
could pass the
String
defining the file name to the constructor. If the icon file is not available then nothing
happens, so the code will work whether or not an icon is defined. We only need to add the code to this
constructor since the other constructors in the
FileAction
class call this one.
The code that you add to the constructors for the
TypeAction
and
ColorAction
inner classes is
exactly the same as here, so go ahead and copy it across.
We can reduce the code we need in the SketchFrame constructor a little by defining a helper method in
the
SketchFrame
class to create toolbar buttons as follows:
private JButton addToolBarButton(Action action) {
JButton button = toolBar.add(action); // Add toolbar button
button.setBorder(BorderFactory.createRaisedBevelBorder());// Add button border
return button;
}
The argument is the
Action
object for the toolbar button that is to be added, and the code is essentially
the same as the specific code we had in the
SketchFrame
constructor to create the button for the
openAction
object. We can remove that from the
SketchFrame
constructor and replace it by the
following code to create all the buttons that we need:
public SketchFrame(String title) {
// Constructor code as before...
// Add file buttons
toolBar.addSeparator(); // Space at the start
addToolBarButton(newAction);
addToolBarButton(openAction);
addToolBarButton(saveAction);
addToolBarButton(printAction);
// Add element type buttons
toolBar.addSeparator();
addToolBarButton(lineAction);
addToolBarButton(rectangleAction);
addToolBarButton(circleAction);
addToolBarButton(curveAction);
// Add element color buttons
toolBar.addSeparator();
addToolBarButton(redAction);
addToolBarButton(yellowAction);
addToolBarButton(greenAction);
addToolBarButton(blueAction);
toolBar.addSeparator(); // Space at the end