代理模式-虚拟代理(image)

来源:互联网 发布:门禁卡读卡器软件 编辑:程序博客网 时间:2024/04/28 15:06

package M_Proxy.image;

import java.awt.Component;
import java.awt.Graphics;
import java.net.URL;

import javax.swing.Icon;
import javax.swing.ImageIcon;

/**
* 设计CD封面虚拟代理
* 1:imageProxy创建imageIcon,开始从网上加载图片
* 2:加载过程中,imageProxy显示CD加载中
* 3:图像加载完毕,imageProxy把所有方法委托给真正的imageIcon对象
* 4:用户请求新的图片,就创建新的代理,重复过程
*/
public class ImageProxy implements Icon {
ImageIcon imageIcon;
URL imageURL;
Thread retrievalThread;
boolean retrieving = false;

public ImageProxy(URL imageURL) {    this.imageURL = imageURL;}// 可以用状态模式优化public int getIconWidth() {    if (imageIcon != null) {        return imageIcon.getIconWidth();    } else        return 800;}// 可以用状态模式优化public int getIconHeight() {    if (imageIcon != null) {        return imageIcon.getIconHeight();    } else {        return 600;    }}@Overridepublic void paintIcon(final Component c, Graphics g, int x, int y) {    if (imageIcon != null)        imageIcon.paintIcon(c, g, x, y);    else {        g.drawString("正在加载请等待", x + 300, y + 190);        // 如果没有取出图片        if (!retrieving) {            retrieving = true;            // 加载图片同步的话,会耗在这里,不能进行其他操作,所以采用多开线程异步加载图片            retrievalThread = new Thread(new Runnable() {                public void run() {                    try {                        // 构造器会在图片加载完后才返回                        imageIcon = new ImageIcon(imageURL, "CD Conver");                        // 图像加载好后,重绘                        c.repaint();                    } catch (Exception e) {                        e.printStackTrace();                    }                }            });            retrievalThread.start();        }    }}

}
package M_Proxy.image;

import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JComponent;

public class ImageComponent extends JComponent {
private Icon icon;

public ImageComponent(Icon icon) {    this.icon = icon;}public void setIcon(Icon icon) {    this.icon = icon;}@Overrideprotected void paintComponent(Graphics g) {    super.paintComponent(g);    int w = icon.getIconWidth();    int h = icon.getIconHeight();    int x = (800 - w) / 2;    int y = (600 - h) / 2;    icon.paintIcon(this, g, x, y);}

}
package M_Proxy.image;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class ImageProxyTestDrive {
ImageComponent imageComponent;
JFrame frame = new JFrame(“CD Conver Viewer”);
JMenuBar menuBar;
JMenu menu;
Hashtable

0 0
原创粉丝点击