日期:2014-05-20  浏览次数:20776 次

关于在jLabel上显示图片,并且图片自适应JLabel的大小
我写了个小程序 打开图片
因为的label(应该说是组件)已经设定了固定大小,
所以再打开一些大图片时,超过组件大小的部分没显示出来?
而小图片又没填充完整个组件

找了一圈 找到一点想法 但是却没实现成功
我把握的实现代码贴出来 大家给看看

首先
Java code

chooser=new JFileChooser();
chooser.setFileView(new FileIconView(filter, new ImageIcon()));



然后在构造了一个类
Java code

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);
                    
                    
                }
            }
        });
    }
}



请大家给点建议
 如果能贴出代码更好



------解决方案--------------------
这组件太小就换个组件贴么..
------解决方案--------------------
icon=new ImageIcon(icon.getImage().getScaledInstance (reImgWidth,reImgHeight, Image.SCALE_DEFAULT));
setIcon(icon);
应该是这个位置不对