Java Reference
In-Depth Information
public final static Color HIGHLIGHT_COLOR = Color.MAGENTA;
To implement the basis for getting highlighting to work, you need to change one line in the
draw()
meth-
od for each of the subclasses of
Element
— that is,
Element.Line
,
Element.Circle
,
Element.Curve
,
Element.Rectangle,
and
Element.Text
. The line to change is the one that sets the drawing color — it's
the first line in each of the
draw()
methods. You should change it to:
g2D.setPaint(highlighted ? HIGHLIGHT_COLOR : color);
Now each element can potentially be highlighted.
The
setHighlighted()
method accepts a
boolean
value as an argument and stores it in the data member
highlighted
. When you want an element to be highlighted, you just call this method with the argument as
true
. To switch highlighting off for an element, you call this method with the argument
false
.
Previously, the
setPaint()
statement just set the color stored in the data member
color
as the drawing
color. Now, if
highlighted
is
true
, the color is set to magenta, and if
highlighted
is
false
, the color
stored in the data member
color
is used.
To make use of highlighting to provide the visual feedback necessary for a user-friendly implementation
of the context menu, you need to determine at all times what is under the cursor. This means you must track
and analyze all mouse moves
all the time
!
Tracking Mouse Moves
Whenever the mouse is moved, the
mouseMoved()
method in the
MouseMotionListener
interface is called.
You can therefore track mouse moves by implementing this method in the
MouseHandler
class that you
defined as an inner class to the
SketcherView
class. Before I get into that, I need to define what I mean
by an element being “under the mouse cursor," and more crucially, how you are going to find out to which
element, if any, this applies at any time.
It's not going to be too difficult. You can arbitrarily decide that an element is “under the mouse cursor"
when the cursor position is inside the bounding rectangle for an element. This is not too precise a method,
but it has the great attraction that it is extremely simple. Precise hit-testing on an element would carry con-
siderably more processing overhead. Electing to add any greater complexity does not help you to understand
the principles here, so you will stick with the simple approach.
So what is going to be the methodology for finding the element under the mouse cursor? Brute force,
basically: Whenever the mouse is moved, you can just search through the bounding rectangles for each of
the elements in the model until you find one that encloses the current cursor position. You then arrange for
the first element that you find to be highlighted. If you check all the elements in the model without finding
a bounding rectangle that encloses the cursor, then there isn't an element under the cursor. The mechanism
for the various geometric elements is illustrated in
Figure 20-14
.