Java Reference
In-Depth Information
This method will also be inherited by all of the sub classes of Element .
To implement the basis for getting highlighting to work, you need to change one line in the draw()
method for each of the sub classes 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 ? Color.MAGENTA : color);
Now each element can potentially be highlighted.
How It Works
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 will be set to magenta, and if highlighted is
false , the color stored in the data member, color , will be used.
To make use of highlighting to provide the visual feedback necessary for a user-friendly implementation
of the context menu, we need to determine at all times what is under the cursor. This means we 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. We can therefore track mouse moves by implementing this method in the MouseHandler
class that is an inner class to the SketchView class. Before we get into that, we need to decide what we
mean by an element being under the cursor, and more crucially, how we are going to find out to which
element, if any, this applies.
Curve is under the
cursor here
Circle is under the
cursor here
bounding
rectangles
Element.Curve
Element.Circle
Rectangle is under
the cursor here
Line is under the
cursor here
Nothing is under the
cursor here
Element.Rectangle
Element.Line
Rectangle bounds = element.getBounds(); // Gets bounding rectangle
bounds.contains(cursor) returns true if cursor is in bounds
Search WWH ::




Custom Search