下面给你提供一个实现,该实现采用了代理模式。这个实现包含两个文件,分别是Client.java和ImageIcoProxy.java,ImageIcoProxy.java负责了图片的延迟加载,你可以修改为不延迟即可。
Client.java的代码为:
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.Icon;
import javax.swing.JFrame;
public class Client extends JFrame {
private static int IMG_WIDTH = 510;
private static int IMG_HEIGHT = 317;
private Icon imgProxy = null;
public static void main(String[] args) {
Client app = new Client();
app.setVisible(true);
}
public Client() {
super("Virture Proxy Client");
imgProxy = new ImageIcoProxy("D:/test.jpg", IMG_WIDTH, IMG_HEIGHT);
this.setBounds(100, 100, IMG_WIDTH + 10, IMG_HEIGHT + 30);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint(Graphics g) {
super.paint(g);
Insets insets = getInsets();
imgProxy.paintIcon(this, g, insets.left, insets.top);
}
}
ImageIcoProxy.java的代码为:
import java.awt.Component;
import java.awt.Graphics;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.SwingUtilities;
public class ImageIcoProxy implements Icon {
private ImageIcon realIcon = null;
private String imgName;
private int width;
private int height;
boolean isIconCreated = false;
public ImageIcoProxy(String imgName, int width, int height) {
this.imgName = imgName;
this.width = width;
this.height = height;
}
public int getIconHeight() {
return realIcon.getIconHeight();
}
public int getIconWidth() {
return realIcon.getIconWidth();
}
public void paintIcon(final Component c, Graphics g, int x, int y) {
if (isIconCreated) {
//已经加载了图片,直接显示
realIcon.paintIcon(c, g, x, y);
g.drawString("Just Test", x + 20, y + 370);
} else {
g.drawRect(x, y, width-1, height-1);
g.drawString("Loading photo...", x+20, y+20);
synchronized(this) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
Thread.currentThread().sleep(2000);
realIcon = new ImageIcon(imgName);
isIconCreated = true;
} catch (Exception e) {
e.printStackTrace();
}
c.repaint();
}
}
);
}
}
}
}
② 如何用java实现下载文件(包括图片)
用流就可以操作,起本质就是复制粘贴。希望对你有所帮助。供参考。
③ java图片显示一半
你看一下图片文件大小,如果图片文件变小了,说明上传的时候图片文件没有完整地被上传,这个时候需要你找一个网络好的地方重新上传。如果图片文件大小一样,把文件下载回本地,用图片工具打开看看图片是不是能完整显示,如果能完整显示,那就是用户那边的网络不够顺畅造成的,如果不能完整显示,则需要你找一个网络好的地方重新上传原图。总之,就是要想办法确定是服务器上图片本身有问题还是用户网络有问题。
④ java在应用程序显示图片
如果想用JLabel实现的话就是JLabel jl = new JLabel(new ImageIcon(/* 图片路径 */));