Java Reference
In-Depth Information
Directory "Sketcher 4 with element type listeners"
You have imported static constants from the Color class, so you can use the names of the standard color
objects that the class defines without qualifying them. When you construct the element objects, you use the
elementType and elementColor members to set the state of each menu item. Only the element type menu
item corresponding to the default type set in elementType is checked because that's the only comparison
that produces a true result as an argument to the JRadioButtonMenuItem constructor. The mechanism is the
same for the color menu items, but note that you use the equals() method defined in the Color class for
a valid comparison of Color objects. You might just get away with using == because you are using only
constant Color values that are defined in the class, but as soon as you use a color that is not one of these,
this would no longer work. Of course, you have to use == for the element type items because the IDs are of
type int .
At this point it would be a good idea to recompile Sketcher to make sure everything is as it should be. Be-
cause you now have your own package containing the SketcherConstants class definition, you must use
the -classpath option to tell the compiler where to find it. Assuming the Constants directory is a subdir-
ectory of the C:/Packages directory, for example, and the current directory is the one containing Sketch-
er.java and SketcherFrame.java , you can use the following command to compile Sketcher:
javac -classpath ".;C:/Packages" Sketcher.java
The -classpath option defines two paths: the current directory, which is specified by the period, and
C:/Packages , which is the path to the Constants directory that contains the SketcherConstants.java
source file. This command should compile everything, including your package.
Having got that sorted out, you can have a go at implementing the listeners for the Elements menu, start-
ing with the type menu items.
TRY IT OUT: Handling Events for the Element Type Menu
You add an inner class to SketcherFrame that defines listeners for the menu items specifying the element
type. This class implements the ActionListener interface because you want to respond to actions on
these menu items. Add the following definition as an inner class to SketcherFrame :
// Handles element type menu items
class TypeListener implements ActionListener {
// Constructor
TypeListener(int type) {
this.type = type;
}
// Sets the element type
public void actionPerformed(ActionEvent e) {
elementType = type;
}
Search WWH ::




Custom Search