Java Reference
In-Depth Information
the cursor is moved out of the area occupied by the component, the mouseExited() method is called,
which restores the default cursor.
Just two extra statements in createGUI() create the listener object and then add it for each selection
button within the loop. If you recompile the applet and run it again, a hand cursor should appear whenev-
er the mouse is over the selection buttons. Of course, you are not limited to just changing the cursor in
the event handler. You could highlight the button by changing its color for instance. You could apply the
same technique for any kind of component where the mouse is the source of actions for it.
SEMANTIC EVENT LISTENERS IN AN
APPLICATION
The Sketcher program is an obvious candidate for implementing semantic event listeners to support the op-
eration of the menu bar in the SketcherFrame class. When you click on an item in one of the drop-down
menus, a semantic event is generated that you can listen for and then use to determine the appropriate pro-
gram action.
Listening to Menu Items
Let's start with the Elements menu. This is concerned with identifying the type of graphic element to be
drawn next, and the color in which it will be drawn. You won't be drawing them for a while, but you can put
in the infrastructure to set the type and color for an element without worrying about how it will actually be
created and drawn.
To identify the type of element, you can define constants that act as IDs for the four types of element
you have provided for in the menu so far. This helps with the operation of the listeners for the menu item as
well as provides a way to identify a particular type of element. Because you'll accumulate quite a number
of application-wide constants, it is convenient to define them as static fields in a class from which they can
be imported statically. To be able to import the static fields, the class must be in a named package, so let's
set that up. To put the class in a package with the name Constants , you need to set up a directory with this
name at a suitable location on your disk, and then use the -classpath option when you compile the class in
the Constants package to identify the path to the Constants directory. Here's the initial definition, includ-
ing constants to define line, rectangle, circle, and curve elements:
// Defines application wide constants
package Constants;
public class SketcherConstants {
// Element type definitions
public final static int LINE = 101;
public final static int RECTANGLE = 102;
public final static int CIRCLE
= 103;
public final static int CURVE
= 104;
// Initial conditions
public final static int DEFAULT_ELEMENT_TYPE = LINE;
Search WWH ::




Custom Search