java如何读取文件夹中的图片并在界面显示

请给出具体代码 多谢了
2024年11月19日 17:40
有2个网友回答
网友(1):

下面给你提供一个实现,该实现采用了代理模式。这个实现包含两个文件,分别是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();
}

}
);
}
}
}

}

网友(2):

1、获取文件夹的路径
2、得到文件夹中的有图片的名称,可以存到数组或者集合中
3、你再到jsp页面做显示,
4、下面是获取路径和文件名的代码,前台显示的代码自己写
String path = 文件夹路径;
String names = "";
try {
File f = new File(path);
if (f.isDirectory())
{
File[] fList = f.listFiles();
for (int j = 0; j < fList.length; j++) {
File file = fList[j]; if (file.isFile())
{
names += file.getName();
}
}
}
} catch (Exception e)
{
}