The problem with the previous applet was that every time the mouse moved, the applet first redrew the background image to erase the previous magnify box, and then redrew the window to display the new magnify box. This resulted in screen flickering. Also the new applet reduces the grey band to one fourth of the box width and height so that when the magnify box is at the edge of the image, the box magnifies the image edge.
Let's look at the differences in the code, which can be found in X.java:
erase_box(box_x, box_y, x, y);As stated, the band around the image is now one-fourth the size of the magnify box width and height instead of one-half like in the previous example. Consequently, we subtract half the box width and height:
if (box_x > (width - box_width/2)) box_x = width - box_width/2; if (box_y > (height - box_height/2)) box_y = height - box_width/2;
g2.drawImage(background, -box_x, -box_y, width*2, height*2, null);
If the user moves the box up and left, the applet must restore the background image below and to the right of the new position of the magnify box. To redraw the image, the applet first defines the clip rectangle for the area beneath the magnify box. Next, the applet can draw the image within that rectangle. Then, before it defines a new clip rectangle for the area to the right of the magnify box, the applet creates another copy of the graphics context. After defining the second clip rectangle, the applet again draws the image within that rectangle:
if (new_x <= old_x && new_y <= old_y) { g2.clipRect(new_x, new_y+box_height, box_width+old_x-new_x, old_y-new_y); g2.drawImage(background, 25, 25, null); g2 = g.create(); g2.clipRect(new_x+box_width, new_y, old_x-new_x, box_height+old_y-new_y); g2.drawImage(background, 25, 25, null); }The other three cases are when the box moves up and right, down and left, and down and right. The code is similar to the code for the case just described (box moving up and left), and is not given here.
g.drawImage(background, box_width/4, box_height/4, this);