我是参照着文件夹显示图片来写的,但是唯一可悲的是效率较慢,希望大神看到我的博客可以给我些建议和方法,而且还有竖滚动栏没动态设置
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class PictureList extends JFrame{
private int sum = 0;
public PictureList(){
this.setSize(450, 400);//设置窗口的大小
JPanel jp = new JPanel();
//jp.setBackground(Color.lightGray);
jp.setLayout(new FlowLayout(FlowLayout.LEFT));//左对齐
JScrollPane jsp = new JScrollPane();
//jsp.add(jp);
//jsp.setLayout(null);
File file =new File("E:\\after");
String[] file1 = file.list();
jp.setBackground(Color.white);
sum += Math.ceil(file1.length*1.0/4)*100;//控制竖滚动条长度:得到个数/4,取上界
jp.setPreferredSize(new Dimension(jsp.getWidth(),sum));//设置
this.setLocationRelativeTo(null);
//jp.setSize(400, 300);
jsp.getViewport().add(jp);
jsp.setVerticalScrollBarPolicy(JScrollPane.
VERTICAL_SCROLLBAR_AS_NEEDED); //设置竖滚动条 需要时出现
jsp.setHorizontalScrollBarPolicy(JScrollPane.
HORIZONTAL_SCROLLBAR_NEVER); //横滚动条,永远不出现
this.getContentPane().add(jsp);
try {
for(int i=0;i<file1.length-1;i++){
FileInputStream fis = new FileInputStream("E:\\after\\"+file1[i]);//文件夹+图片名
BufferedImage bi = ImageIO.read(fis);
ImageIcon icon = new ImageIcon(bi);
fis.close();
JButton jb = new JButton();
//jb.setSize(159, 350);
jb.setIcon(icon);
int width =icon.getIconWidth();
int height = icon.getIconHeight();
if(width>95){//设置长宽
if(height >95){//长宽都比95大
if((width-95)>( height-95)){//判断长离95近还是宽离95近
height = height*95/width;
width = 95;
}else{
width = width*95/height;
height = 95;
}
}else{//长比95大,宽比95小
height = height*95/width;
width = 95;
}
}else{
if(height<95){//长宽都比95小
if((95-width)> (95-height)){
height = height*95/width;
width = 95;
}else{
width = width*95/height;
height = 95;
}
}else{//长比95小,宽95大
width = width*95/height;
height = 95;
}
}
//System.out.println(width+" "+height);
// if(Math.max(Math.abs(width-95), Math.abs(height-95))>0){
//
// }
icon.setImage(icon.getImage().getScaledInstance(width, height, Image.SCALE_DEFAULT));
jb.setPreferredSize(new Dimension(95,95));
jb.setBackground(Color.white);
//jb.setBorder(null);
jp.add(jb);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}