在JLabel上显示图片,并且图片自适应JLabel的大小

本文转载地址:

      http://blog.csdn.net/xiaoliangmeiny/article/details/7060250

 


 

      在写《Core Java》上的示例代码时,其中有一个FileChooserTest是打开一张图片,并在Label上显示出来,但是这个示例程序有缺点,由于窗口的大小已经固定,而选择打开的图片有大有小,如果图片比窗口大,则超过框口部分的则被隐藏没显示出来,要靠拖动窗口才能显示其余部分,若图片比较小,则打开在窗口中显得过小,于是稍作了修改。使得打开的图片可以完全根据窗口大小调整自身大小,也可以根据窗口的宽等比缩放。由于之前在网上搜索发现不少人遇到同样的问题,且大都没有有效解决掉,故把代码贴出来:

 

  1. package FileChooserTest;  
  2.   
  3. import java.awt.BorderLayout;  
  4. import java.awt.Dimension;  
  5. import java.awt.EventQueue;  
  6. import java.awt.Image;  
  7. import java.awt.event.ActionEvent;  
  8. import java.awt.event.ActionListener;  
  9. import java.beans.PropertyChangeEvent;  
  10. import java.beans.PropertyChangeListener;  
  11. import java.io.File;  
  12.   
  13. import javax.swing.BorderFactory;  
  14. import javax.swing.Icon;  
  15. import javax.swing.ImageIcon;  
  16. import javax.swing.JFileChooser;  
  17. import javax.swing.JFrame;  
  18. import javax.swing.JLabel;  
  19. import javax.swing.JMenu;  
  20. import javax.swing.JMenuBar;  
  21. import javax.swing.JMenuItem;  
  22. import javax.swing.SwingConstants;  
  23. import javax.swing.UIManager;  
  24. import javax.swing.UnsupportedLookAndFeelException;  
  25. import javax.swing.filechooser.FileFilter;  
  26. import javax.swing.filechooser.FileNameExtensionFilter;  
  27. import javax.swing.filechooser.FileView;  
  28.   
  29. public class FileChooserTest {  
  30.   
  31.     public static void main(String[] args) {  
  32.         EventQueue.invokeLater(new Runnable() {  
  33.             public void run() {  
  34.                 ImageViewerFrame frame = new ImageViewerFrame();  
  35.                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  36.                 frame.setVisible(true);  
  37.             }  
  38.         });  
  39.     }  
  40. }  
  41.   
  42. class ImageViewerFrame extends JFrame {  
  43.       
  44.     public ImageViewerFrame() {  
  45.         super("ImageViewer");  
  46.         setSize(WIDTH, HEIGHT);  
  47.         try {  
  48.             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());  
  49.         } catch (Exception e) {  
  50.             //  
  51.         }   
  52.   
  53.         JMenuBar menuBar = new JMenuBar();  
  54.         setJMenuBar(menuBar);  
  55.         JMenu menu = new JMenu("File");  
  56.         JMenuItem openItem = new JMenuItem("open");  
  57.         menu.add(openItem);  
  58.         openItem.addActionListener(new FileOpenListener());  
  59.         JMenuItem exitItem = new JMenuItem("exit");  
  60.         menu.add(exitItem);  
  61.         menuBar.add(menu);  
  62.         exitItem.addActionListener(new ActionListener() {  
  63.             public void actionPerformed(ActionEvent e) {  
  64.                 // TODO Auto-generated method stub  
  65.                 System.exit(0);  
  66.             }  
  67.         });  
  68.           
  69.         //use a label to display a image  
  70.         label =new JLabel();  
  71.         add(label,BorderLayout.CENTER);  
  72.           
  73.         chooser=new JFileChooser();  
  74.         FileNameExtensionFilter filter =new FileNameExtensionFilter("Image Files""jpg","jpeg","gif");  
  75.         chooser.setFileFilter(filter);  
  76.         //预览  
  77.         chooser.setAccessory(new ImagePreviewer(chooser));  
  78.         //accessory 通常用于显示已选中文件的预览图像  
  79.           
  80. //      chooser.setFileView(new FileIconView(filter,new ImageIcon("palette.gif")));  
  81.         chooser.setFileView(new FileIconView(filter, new ImageIcon()));  
  82.         //设置用于检索 UI 信息的文件视图,如表示文件的图标或文件的类型描述。   
  83.   
  84.     }  
  85.       
  86.     private class FileOpenListener implements ActionListener{  
  87.         @Override  
  88.         public void actionPerformed(ActionEvent e) {  
  89.             // TODO Auto-generated method stub  
  90.             chooser.setCurrentDirectory(new File("."));  
  91.             int result=chooser.showOpenDialog(ImageViewerFrame.this);  
  92.             if(result==JFileChooser.APPROVE_OPTION){  
  93.                 String name=chooser.getSelectedFile().getPath();  
  94.                 ImageIcon icon=new ImageIcon(name);  
  95. //              等比缩放条件  
  96. //              int imgWidth=icon.getIconWidth();  
  97. //              int imgHeight=icon.getIconHeight();  
  98. //              int conWidth=getWidth();  
  99. //              int conHeight=getHeight();  
  100. //              int reImgWidth;  
  101. //              int reImgHeight;  
  102. //              if(imgWidth/imgHeight>=conWidth/conHeight){  
  103. //                  if(imgWidth>conWidth){  
  104. //                      reImgWidth=conWidth;  
  105. //                      reImgHeight=imgHeight*reImgWidth/imgWidth;  
  106. //                  }else{  
  107. //                      reImgWidth=imgWidth;  
  108. //                      reImgHeight=imgHeight;  
  109. //                  }  
  110. //              }else{  
  111. //                  if(imgWidth>conWidth){  
  112. //                      reImgHeight=conHeight;  
  113. //                      reImgWidth=imgWidth*reImgHeight/imgHeight;  
  114. //                  }else{  
  115. //                      reImgWidth=imgWidth;  
  116. //                      reImgHeight=imgHeight;  
  117. //                  }  
  118. //              }  
  119.                 //这个是强制缩放到与组件(Label)大小相同  
  120.                 icon=new ImageIcon(icon.getImage().getScaledInstance(getWidth(), getHeight()-25, Image.SCALE_DEFAULT));  
  121.                 //这个是按等比缩放  
  122. //              icon=new ImageIcon(icon.getImage().getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_DEFAULT));  
  123.                 label.setIcon(icon);  
  124.                 label.setHorizontalAlignment(SwingConstants.CENTER);  
  125.             }  
  126.         }  
  127.     }  
  128.   
  129.     public static final int WIDTH = 500;  
  130.     public static final int HEIGHT = 500;  
  131.       
  132.     private JLabel label;  
  133.     private JFileChooser chooser;  
  134. }  
  135.     
  136. class FileIconView extends FileView {  
  137.     public FileIconView(FileFilter aFilter,Icon anIcon){  
  138.         filter=aFilter;  
  139.         icon=anIcon;  
  140.     }  
  141.     public Icon getIcon(File f){  
  142.         if(!f.isDirectory()&&filter.accept(f)){  
  143.             return icon;  
  144.         }else return null;  
  145.     }  
  146.     private FileFilter filter;  
  147.     private Icon icon;  
  148. }  
  149.   
  150. class ImagePreviewer extends JLabel{  
  151.     public ImagePreviewer(JFileChooser chooser){  
  152.         setPreferredSize(new Dimension(100,100));  
  153.         setBorder(BorderFactory.createEtchedBorder());  
  154.         chooser.addPropertyChangeListener(new PropertyChangeListener() {  
  155.             public void propertyChange(PropertyChangeEvent event) {  
  156.                 if(event.getPropertyName()==JFileChooser.SELECTED_FILE_CHANGED_PROPERTY){  
  157.                     File f=(File) event.getNewValue();  
  158.                     if(f==null){  
  159.                         setIcon(null);  
  160.                         return;  
  161.                     }  
  162.                     ImageIcon icon=new ImageIcon(f.getPath());  
  163. //                  if(icon.getIconWidth()>getWidth()){  
  164.                         icon=new ImageIcon(icon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));  
  165. //                  }  
  166.                     setIcon(icon);  
  167.                 }  
  168.             }  
  169.         });  
  170.     }  
  171. }  

 选择等比缩放还是完全自适应,看代码注释处切换。


posted @ 2015-03-27 13:06  YGingko  阅读(3532)  评论(0编辑  收藏  举报