Java Reference
In-Depth Information
As you drag the mouse with the button down, we'll display the line as it looks at that point. Thus the
line will be displayed dynamically all the time the mouse cursor is being dragged and the left button
remains pressed. This process is called rubber-banding .
We can use essentially the same process of pressing the mouse button and dragging the cursor for all
four of our shapes. Thus two points will define each shape - the cursor position where the mouse button
is pressed, and the cursor position where the mouse button is released, (plus the color for the shape, of
course). This implies that our shape constructors will all have three parameters, the two points and the
color. Let's look at how we handle mouse events to make this work.
Handling Mouse Events
Because all the drawing operations for a sketch will be accomplished using the mouse, we must
implement the process for creating elements within the methods that will handle the mouse events. The
mouse events we're interested in will originate in the SketchView object because that's where we'll be
drawing shapes. We will make the view responsible for handling all its own events, which will include
events that occur in the drawing process as well as interactions with existing shapes.
Drawing a shape, such as a line, interactively will involve us in handling three different kinds of mouse
event. Let's summarize what they are, and what we need to do when they occur:
Event
Action
Left Button (Button 1)
pressed
Save the cursor position somewhere as the starting point
for the line. We'll store this in a data member of the inner
class to SketchView that we'll create to define listeners
for mouse events.
Mouse dragged
Save the current cursor position somewhere as the end
point for the line. Erase any previously drawn temporary
line, and create a new temporary line from the starting
point that was saved initially. Draw the new temporary
line.
Left Button (Button 1)
released
If there's a reference to a temporary line stored, add it to
the sketch model, and redraw it.
You'll remember from the previous chapter that there are two mouse listener interfaces:
MouseListener which has methods for handling events that occur when the mouse buttons are
pressed or released and MouseMotionListener which has methods for handling events that arise
when the mouse is moved. You will also recall that the MouseInputAdapter class implements both,
and since we need to implement methods from both interfaces, we'll add an inner class to the
SketchView class that extends the MouseInputAdapter class.
Since there's quite a lot of code involved in this, we will first define the bare bones of the class to handle
mouse events, and then build in the detail until it does what we want.
Search WWH ::




Custom Search