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

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

 

package FileChooserTest;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;

import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileView;

public class FileChooserTest {

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				ImageViewerFrame frame = new ImageViewerFrame();
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				frame.setVisible(true);
			}
		});
	}
}

class ImageViewerFrame extends JFrame {
	
	public ImageViewerFrame() {
		super("ImageViewer");
		setSize(WIDTH, HEIGHT);
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			//
		} 

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);
		JMenu menu = new JMenu("File");
		JMenuItem openItem = new JMenuItem("open");
		menu.add(openItem);
		openItem.addActionListener(new FileOpenListener());
		JMenuItem exitItem = new JMenuItem("exit");
		menu.add(exitItem);
		menuBar.add(menu);
		exitItem.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				System.exit(0);
			}
		});
		
		//use a label to display a image
		label =new JLabel();
		add(label,BorderLayout.CENTER);
		
		chooser=new JFileChooser();
		FileNameExtensionFilter filter =new FileNameExtensionFilter("Image Files", "jpg","jpeg","gif");
		chooser.setFileFilter(filter);
		//预览
		chooser.setAccessory(new ImagePreviewer(chooser));
		//accessory 通常用于显示已选中文件的预览图像
		
//		chooser.setFileView(new FileIconView(filter,new ImageIcon("palette.gif")));
		chooser.setFileView(new FileIconView(filter, new ImageIcon()));
		//设置用于检索 UI 信息的文件视图,如表示文件的图标或文件的类型描述。 

	}
	
	private class FileOpenListener implements ActionListener{
		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			chooser.setCurrentDirectory(new File("."));
			int result=chooser.showOpenDialog(ImageViewerFrame.this);
			if(result==JFileChooser.APPROVE_OPTION){
				String name=chooser.getSelectedFile().getPath();
				ImageIcon icon=new ImageIcon(name);
//				等比缩放条件
//				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;
//					}
//				}
				//这个是强制缩放到与组件(Label)大小相同
				icon=new ImageIcon(icon.getImage().getScaledInstance(getWidth(), getHeight()-25, Image.SCALE_DEFAULT));
                //这个是按等比缩放
//				icon=new ImageIcon(icon.getImage().getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_DEFAULT));
				label.setIcon(icon);
				label.setHorizontalAlignment(SwingConstants.CENTER);
			}
		}
	}

	public static final int WIDTH = 500;
	public static final int HEIGHT = 500;
	
	private JLabel label;
	private JFileChooser chooser;
}
  
class FileIconView extends FileView {
	public FileIconView(FileFilter aFilter,Icon anIcon){
		filter=aFilter;
		icon=anIcon;
	}
	public Icon getIcon(File f){
		if(!f.isDirectory()&&filter.accept(f)){
			return icon;
		}else return null;
	}
	private FileFilter filter;
	private Icon icon;
}

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.getPath());
//					if(icon.getIconWidth()>getWidth()){
						icon=new ImageIcon(icon.getImage().getScaledInstance(getWidth(), -1, Image.SCALE_DEFAULT));
//					}
					setIcon(icon);
				}
			}
		});
	}
}

 

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


嘿嘿,各位写代码也有点累了吧,特别是深夜的时候是不是觉得应该有点吃的就更好了?可以到本人开


的小店“小灰灰休闲美食”店买点休闲食品哦,既满足食欲又可以放松哈子,当然平时也要吃是吧,也


可以买来送朋友哦!


你可能感兴趣的:(exception,filter,File,null,Class)