Help: Double-buffering


Help is available for each task, or you can go straight to the solution source code.

Task 1

Modify class SimpleDrawingRegion. Define a background buffer and graphics context for it as instance variables buffer and bufferGr. In the constructor, create an image according to the width and height passed in and then obtain the graphics context. See Image and Graphics.
To create the image, you will need to reference method applet.createImage where applet is passed in to the constructor.

Task 2

Define update so that it simply calls paint. Normally it clears the graphics region before calling paint. Because we will copy over the entire graphics region in our paint, it is a waste of time and a source of flicker to have update erase the screen.

Task 3

Define paint so that it copies the background buffer on the canvas. Draw a border around the canvas 0,0,width-1,height-1.
To copy the background buffer onto the visible canvas region, use drawImage of Graphics. The first argument is the buffer to draw, the next two are the coordinates of where to place it (use 0,0), and the last argument is the image observer (use this); the image observer, the drawing region in this case, gets notified when the image has been completely drawn, which is unnecessary information for this application.

Task 4

Define mouse down to set the upper-left corner of the rectangle (downX, downY). Just like in the rubberbanding Magercise. Reset width and height (w, h).

Task 5

Define mouseDrag so that it erases the old image on the visible canvas and draws an updated image at new location. Use XOR mode so the background image is not disturbed. Use method clip to restrict the dragging to the region of the canvas. Draw the rubberbanding rectangle in red, but draw final rectangle in black.
We have computed the correct XOR color for you so that setting the XOR mode with this will make rubberbanding occur in red. Later in mouseUp we will draw a rectangle in black on the background buffer.

Set the XOR mode with Graphics.setXORMode. You will have to pass it new Color object.

Draw a rectangle at downX, downY, w, h to erase. Then, compute new w,h (w = clipped.x - downX) and use the same draw rectangle command, but with the new w,h.

Task 6

Define mouseUp to draw a rectangle on the background buffer and call repaint to schedule a canvas repaint.
Call repaint to schedule a repaint.

Copyright © 1996-1997 MageLang Institute. All Rights Reserved.