Java Reference
In-Depth Information
cursor
if(element==highlightElement) {
// If it's
already highlighted
return;
// we are done
}
// Un-highlight any existing highlighted element
if(highlightElement!= null) {
// If an element
is highlighted
highlightElement.setHighlighted(false); // un-highlight
it and
repaint(highlightElement.getBounds()); //... redraw it
}
element.setHighlighted(true);
// Set highlight
for new element
highlightElement = element;
// Store new
highlighted element
repaint(highlightElement.getBounds());
return;
}
}
// Here there is no element under the cursor so...
if(highlightElement!=null)
{
// If an element is
highlighted...
highlightElement.setHighlighted(false); // ...turn off
highlighting...
repaint(highlightElement.getBounds());
// ... and redraw
the element
highlightElement = null;
// No element
highlighted
}
}
Directory "Sketcher 6 highlighting elements"
To check that highlighting works, recompile Sketcher and run it again. If you draw a few elements, you
should see them change color as the cursor moves over them.
How It Works
This method is a fair amount of code, so let's work through it step by step. The first statement saves the
current cursor position in the local variable currentCursor . You use a collection-based for loop to iter-
ate over all the elements in the model. In the loop, you obtain the bounding rectangle for each element by
calling its getBounds() method, and then call the contains() method for the rectangle that is returned
with the current cursor position as the argument. This returns true if the rectangle encloses the point and
returns false if it doesn't.
When you find an element under the cursor, it is quite possible that the element is already highlighted
because the element was found and highlighted the last time the mouseMoved() method was called. This
occurs when you move the cursor within the rectangle bounding an element. In this case you don't need
to do anything, so you return from the method.
Search WWH ::




Custom Search