O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

19.7. Drawing Using the Mouse

You've drawn shapes so far just using data internal to the program. In the Sketcher program you want to be able to draw a shape using the mouse in the view and then store the finished shape in the model. Ideally, the process should be as natural as possible, so you'll implement a mechanism that allows you to draw by pressing the left mouse button (more accurately, button 1) and dragging the cursor to draw the selected type of shape. So for a line, the point where you depress the mouse button will be the start point for the line, and the point where you release the button will be the end point. This process is illustrated in Figure 19-23.

As the user drags the mouse with the button down, Sketcher will 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.

You can use essentially the same process of pressing the mouse button and dragging the cursor for all four of the shapes you saw when I discussed the Element class. 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 the shape constructors will all have three parameters, corresponding to the two points and the color. Let's look at how you handle mouse events to make this work.

Figure ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required