為了代替那些純粹的、可繪制圖形的對象,AWT 使用了一種簡單的模式。每個 AWT 構件完全來自于它自己的 java.awt.Graphics 對象。
java.awt.Graphics 是一個抽象類,其作用是定義一個真正的工具,用來接受圖形操作。
表一:傳遞一個對 Graphics 的引用的 JDK 方法
java.awt | Canvas | paint(Graphics g) |
Component | paint(Graphics g) | |
Component | paintAll(Graphics g) | |
Component | print(Graphics g) | |
Component | printAll(Graphics g) | |
Component | update(Graphics g) | |
Container | paint(Graphics g) | |
Container | paintComponents(Graphics g) | |
Container | print(Graphics g) | |
Container | printComponents(Graphics g) | |
ScrollPane | printComponents(Graphics g) | |
java.beans | Property-Editor | paintValue(Graphics g, Rectangle r) |
Property-EditorSupport | paintValue(Graphics g, Rectangle r) |
表二:返回 Graphics 引用的 JDK 方法
java.awt | Component | getGraphics() |
Image | getGraphics() | |
PrintJob | getGraphics() | |
Graphics | create() | |
Graphics | create(intx, int y, int w, int h) |
Graphics 類履行2個主要的職責:
· 設置和獲取圖形參數。
· 在輸出設備中執行圖形操作。
得到構件的 Graphics 的引用有2種方法:
· 重載 表一 中的方法(傳遞 Graphics 的引用)
· 調用 表二 中的方法(返回 Graphics 的副本)
Graphics 對象的壽命
除了使用 表二 的方法得到的 Graphics 的副本外,使用 表一 的方法得到的 Graphics 的引用只有在方法的執行過程中才有效(例如重載的 paint() 和 update() 等方法)。一旦方法返回,引用將不再有效。
通過使用 表二 的方法得到的 Graphics 的對象使用完后需要調用 Graphics.dispose() 方法處理。
// 程序片斷
public void someMethodInAComponent(){
Graphics g = getGraphics();
if(g != null){
try{
// ...
// ...
}
finally{
g.dispose();
}
}
}
Graphics 類還提供2個方法創建 Graphics 對象:
· Graphics create()
創建精確的 Graphics 副本。
· Graphics create(int x, int y, int w, int h)
創建一個副本,但是,變元指定一個平移量 (x, y) 和一個新的剪貼矩形 (x, y, w, h)。create(int, int, int, int) 返回的 Graphics 的原點被轉換成 (x, y) 的坐標,但是剪貼矩形轉換為原剪貼矩形和指定矩形的交集。
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
public class CreateTest extends Applet{
private Image image;
public void init(){
image = getImage(getCodeBase(),"lena.jpg");
try{
MediaTracker mt = new MediaTracker(this);
mt.addImage(image,0);
mt.waitForID(0);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
public void paint(Graphics g){
Graphics copy = g.create(image.getWidth(this),0,image.getWidth(this),image.getHeight(this));
try{
System.out.println("g: " + g.getClip().toString());
System.out.println("copy: " + copy.getClip().toString());
g.drawImage(image,0,0,this);
copy.drawImage(image,0,0,this);
}
finally{
copy.dispose();
}
}
}