If a programmer wants to temporarily set the clip to a smaller area for one or two rendering operations and then restore it later, then another mechanism must be used. The currently available work-around is to copy the Graphics object using one of the create() methods and then set the temporary clip on the new Graphics object using the clipRect method and dispose of it when done. The original Graphics object will still have its original clip unmodified and can be used for further rendering.
Furthermore, all of the other attributes of the Graphics object can be queried, changed, and then restored to their original values. The clip area, when viewed as a rendering attribute, only partially follows this design model. There is a getClipRect() method to query the clip area as a Rectangle object, but that method is not extensible in the future when non-rectangular clip areas may be provided. In addition, even if you queried the current clip area there was no way to explicitly set the clip to this value after you have installed a more restrictive clip.
java.awt.Shape
is being added to the AWT and 3 new methods:
getClip()
setClip(Shape)
setClip(int x, int y, int w, int h)
are being added to the AWT Graphics class.
In addition, the getClipRect() method is now deprecated in favor
of the more general getClip() method detailed above and a new method:
getClipBounds()
which returns the bounding box of the current clip area as a Rectangle
regardless of its shape.
This method is also named consistently with the recent terminology
updates that were implemented across the AWT classes.
Following is sample code showing the use of the old API to perform
temporary clipping:
import java.awt.*;
import java.applet.*;
public class TempClipExample extends Applet {
Image bgimg, img2;
public void paint(Graphics g) {
// Draw a background image
g.drawImage(bgimg, 0, 0, this);
// Draw the upper left 100x100 portion of another image at 10,10
Graphics g2 = g.create();
g2.clipRect(10, 10, 100, 100);
g2.drawImage(img2, 10, 10, this);
g2.dispose(); // reclaims resources more quickly
// Now continue drawing with original clip area
g.fillRect(0, 0, 10, 10);
}
}
Following is sample code showing the use of the new API to perform
temporary clipping:
import java.awt.*;
import java.applet.*;
public class TempClipExample extends Applet {
Image bgimg, img2;
public void paint(Graphics g) {
// Draw a background image
g.drawImage(bgimg, 0, 0, this);
// Draw the upper left 100x100 portion of another image at 10,10
Shape oldclip = g.getClip();
g.clipRect(10, 10, 100, 100);
g.drawImage(img2, 10, 10, this);
g.setClip(oldclip);
// Now continue drawing with original clip area
g.fillRect(0, 0, 10, 10);
}
}