JFileChooser_2

JFileChooser_2JFileChooser_2JFileChooser_2

package com.han;

import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.filechooser.FileNameExtensionFilter;

public class JFileChooser_2 extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5653812191066673849L;
	
	static Dimension dimension;
	static JFileChooser_2 frame;

	public JFileChooser_2() {
		// TODO Auto-generated constructor stub
		final JLabel label = new JLabel("<双击选择图片>", SwingConstants.CENTER);
		getContentPane().add(label);
		dimension = getContentPane().getPreferredSize();
		// System.out.println(dimension.width + "\t" + dimension.height);
		label.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount() == 2) {
					JFileChooser fileChooser = new JFileChooser();
					FileNameExtensionFilter filter = new FileNameExtensionFilter(
							"图像文件(JPG)", "JPG", "JPEG");
					FileNameExtensionFilter filter2 = new FileNameExtensionFilter(
							"图像文件(JPG/PNG)", "JPG", "JPEG", "PNG");
					FileNameExtensionFilter filter3 = new FileNameExtensionFilter(
							"图像文件(JPG/PNG/GIF)", "JPG", "JPEG", "PNG", "GIF");
					fileChooser.addChoosableFileFilter(filter);
					fileChooser.addChoosableFileFilter(filter2);
					fileChooser.addChoosableFileFilter(filter3);
					// Sets the current file filter. 
					fileChooser.setFileFilter(filter2); 
					//fileChooser.setAcceptAllFileFilterUsed(false);
					int i = fileChooser.showOpenDialog(getContentPane());
					if (i == JFileChooser.APPROVE_OPTION) {
						File file = fileChooser.getSelectedFile();
						label.setIcon(new ImageIcon(file.getAbsolutePath()));
						dimension = getContentPane().getPreferredSize();
						// we have to consider the title bar's height and the two border sides
						dimension = new Dimension(dimension.width + 50, dimension.height + 50);
						frame.setSize(dimension);
					}
				}
			}
		});
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		frame = new JFileChooser_2();
		frame.setTitle("选择照片对话框");
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		// we have to consider the title bar's height
		dimension = new Dimension(dimension.width + 50, dimension.height + 50);
		frame.setSize(dimension);
	}

}


你可能感兴趣的:(JFileChooser)