[關(guān)鍵字]:java,design pattern,設(shè)計(jì)模式,《Java與模式》學(xué)習(xí),Proxy Pattern,代理模式
[環(huán)境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com) http://wintys.blogjava.net
[正文]:
虛擬代理:

package pattern.proxy.virtual;
import java.awt.Graphics;
import java.awt.Component;
import java.awt.Insets;
import java.awt.Container;
import javax.swing.JPanel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.Icon;
/**
* 虛擬代理
*
* 使用代理加載圖片
*
* @version 2009-6-29
* @author Winty(wintys@gmail.com) http://wintys.blogjava.net
*/
public class VirtualProxyTest extends JFrame{
private final int WIDTH = 500;
private final int HEIGHT = 500;
public VirtualProxyTest(){
super("虛擬代理");
setContentPane(new MyPanel());
setSize(WIDTH , HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args){
VirtualProxyTest test = new VirtualProxyTest();
}
}
class MyPanel extends JPanel{
private IconProxy iconProxy;
public MyPanel(){
iconProxy = new IconProxy("sample.jpg" , 200 , 20);
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
iconProxy.paintIcon(this , g , 0 , 0);
}
}
class IconProxy implements Icon{
private Icon icon;
private String fileName;//Icon的文件名
private boolean done;//Icon是否加載完成
private final int STR_X;
private final int STR_Y;
/**
* @param fileName 圖片文件
* @param str_x 字符串輸出的x位置
* @param str_y 字符串輸出的y位置
*/
public IconProxy(String fileName , int str_x , int str_y){
icon = null;
this.fileName = fileName;
done = false;
STR_X = str_x;
STR_Y = str_y;
}
@Override
public int getIconHeight(){
return icon.getIconHeight();
}
@Override
public int getIconWidth(){
return icon.getIconWidth();
}
@Override
public void paintIcon(final Component c, Graphics g, int x, int y){
//因?yàn)镴Frame的標(biāo)題欄和邊框占據(jù)了空間,
//而paintIcon是從容器的(0,0)坐標(biāo)開始繪制,所以要計(jì)算邊框所占的空間。
Insets inset = new Insets(0,0,0,0);
if(c instanceof Container)
inset = ((Container)c).getInsets();
if(!done){//未加載完成
g.drawString("Loading icon...",
inset.right + STR_X ,
inset.top + STR_Y);
synchronized(this){
SwingUtilities.invokeLater(
new Runnable(){
public void run(){
//延時(shí)
try{
Thread.sleep(5*1000);
}catch(InterruptedException e){
JOptionPane.showMessageDialog(c , e.getMessage());
}
icon = new ImageIcon(fileName);
done = true;
c.repaint();
}
}
);
}//end of synchronized
}
else{//加載完成
g.drawString("Loaded successfully.",
inset.right + STR_X ,
inset.top + STR_Y);
//空出長(zhǎng)度為STR_Y的空間給String
icon.paintIcon(c , g , x + inset.right , y + inset.top + STR_Y + 5);
}
}
}
運(yùn)行結(jié)果:
Loading icon...
Loaded successfully:
posted on 2009-06-29 22:41
天堂露珠 閱讀(1293)
評(píng)論(0) 編輯 收藏 所屬分類:
Pattern