日期:2014-05-20 浏览次数:20704 次
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.io.File; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class ThumbnailPanel extends JPanel { private File PraFile; //根目录 private String[] SubFile; //根目录下文件名 private String[] ImgPath; //根目录下能识别图像 private ImageIcon[] Img; //图片文件 private Image[] Thumbnail; //缩略图 private int ImgCount; //图片数目 private JPanel[] JpThum; //用于装载缩略图+文件名 private JPanel[] JpPic; //用于装载缩略图 private JLabel[] Pic; private JPanel[] JpTex; private JLabel[] Name; ThumbnailPanel(String PraPath) { ImgPath = new String[1000]; Img = new ImageIcon[1000]; Thumbnail = new Image[1000]; ImgCount = 0; JpThum = new JPanel[1000]; Pic = new JLabel[1000]; Name = new JLabel[1000]; JpPic = new JPanel[1000]; JpTex = new JPanel[1000]; loadImg(PraPath); paintPanel(); } public Image getThumbnail(ImageIcon Img) { //根据图片宽和高的比例选择缩放 Image img; if (Img.getIconHeight() > Img.getIconWidth()) { img = Img.getImage().getScaledInstance(-100, 100, 1); } else { img = Img.getImage().getScaledInstance(100, -100, 1); } return img; } public void loadImg(String PraPath) { //将根目录下图片格式的文件读入图片数组 //装载目录下图片文件名 PraFile = new File(PraPath); SubFile = PraFile.list(); for (int i = 0; i < SubFile.length; ++i) { if (SubFile[i].contains(".jpeg") || SubFile[i].contains(".png") || SubFile[i].contains(".jpg") || SubFile[i].contains(".gif")) { ImgPath[ImgCount++] = "D:/javapic/" + SubFile[i]; } } //装载图片和缩略图 for (int i = 0; i < ImgCount; ++i) { Img[i] = new ImageIcon(ImgPath[i]); Thumbnail[i] = getThumbnail(Img[i]); } } public void paintPanel() { //载入到缩略图面板 for (int i = 0; i < ImgCount; ++i) { Pic[i] = new JLabel(new ImageIcon(Thumbnail[i])); Name[i] = new JLabel(ImgPath[i].replace("D:/javapic/", ""), JLabel.CENTER); Name[i].setBorder(BorderFactory.createEmptyBorder()); JpThum[i] = new JPanel(); JpPic[i] = new JPanel(new BorderLayout()); JpPic[i].add(Pic[i], "South"); JpPic[i].setPreferredSize(new Dimension(100, 100)); JpTex[i] = new JPanel(new BorderLayout()); JpTex[i].add(Name[i], "North"); JpTex[i].setPreferredSize(new Dimension(100, 35)); Dimension a = new Dimension(100, 135); JpThum[i].setPreferredSize(a); JpThum[i].add(JpPic[i], "North"); JpThum[i].add(JpTex[i], "South"); } GridBagLayout gridbag = new GridBagLayout(); GridBagConstraints c = new GridBagConstraints(0,0,1,1,0,0,GridBagConstraints.EAST,GridBagConstraints.NONE,new Insets(150,150,150,150),100,100); for (int i = 0; i < ImgCount; ++i) { gridbag.setConstraints(JpThum[i], c);//结果表明用了跟直接add是一样的 add(JpThum[i]); } } public static void main(String[] args) { ThumbnailPanel tp = new ThumbnailPanel("D:/javapic/"); JFrame jf = new JFrame(); jf.add(tp); jf.pack(); jf.setSize(600, 600); jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jf.setVisible(true); } }