日期:2014-05-20 浏览次数:20877 次
chooser=new JFileChooser(); chooser.setFileView(new FileIconView(filter, new ImageIcon()));
class ImagePreviewer extends JLabel{ public ImagePreviewer(JFileChooser chooser){ setPreferredSize(new Dimension(100,100)); setBorder(BorderFactory.createEtchedBorder()); chooser.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent event) { if(event.getPropertyName()==JFileChooser.SELECTED_FILE_CHANGED_PROPERTY){ File f=(File) event.getNewValue(); if(f==null){ setIcon(null); return; } ImageIcon icon=new ImageIcon(f.getName()); int imgWidth=icon.getIconWidth();//获得图片宽度 int imgHeight=icon.getIconHeight();//获得图片高度 int conWidth=getWidth();//得到组件宽度 int conHeight=getHeight();//得到组件高度 int reImgWidth;//保存图片更改宽度后的值 int reImgHeight;//保存图片更改高度后的值 if(imgWidth/imgHeight>=conWidth/conHeight){ if(imgWidth>conWidth){ reImgWidth=conWidth; reImgHeight=imgHeight*reImgWidth/imgWidth; }else{ reImgWidth=imgWidth; reImgHeight=imgHeight; } }else{ if(imgWidth>conWidth){ reImgHeight=conHeight; reImgWidth=imgWidth*reImgHeight/imgHeight; }else{ reImgWidth=imgWidth; reImgHeight=imgHeight; } } icon=new ImageIcon(icon.getImage().getScaledInstance (reImgWidth,reImgHeight, Image.SCALE_DEFAULT)); setIcon(icon); } } }); } }