[改编]JFileChooser学习
import javax.swing.filechooser.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.beans.*;
public class FileChooserDemo extends JFrame {
private static final long serialVersionUID = 1L;
private JButton btn1, btn2, btn3;
private JTextArea area;
private JScrollPane scroll;
private JPanel panel;
public FileChooserDemo() {
super("FileChooser Demo");
btn1 = new JButton("Open Directory");
btn1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
int result = choose.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION){
File file = choose.getSelectedFile();
if (!file.exists())
area.append("File does not exist~!\n");
else if (file.isDirectory()) {
area.append("Directory " + file.getName()
+ " containt following files: \n");
for (int i = 0; i < file.list().length; i++)
area.append(file.list()[i] + " ");
area.append("\n");
} else if (file.isFile())
area.append("It is a file, please use the second button to hava another test\n");
} else
return;
}
});
btn2 = new JButton("Open a file");
btn2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser choose = new JFileChooser();
choose.setFileSelectionMode(JFileChooser.FILES_ONLY);
int result = choose.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION){
File file = choose.getSelectedFile();
if (!file.exists())
area.append("File does not exist~!\n");
else {
try {
ObjectOutputStream output = new ObjectOutputStream(
new FileOutputStream(file));
// ..tobeContinued
} catch (IOException ioexception) {
area.append(ioexception.toString()+"\n");
}
}
} else
return;
}
});
btn3 = new JButton("Images File Filter");
btn3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser choose = new JFileChooser();
ImagePreviewPanel preview = new ImagePreviewPanel();
choose.setAccessory(preview);
choose.addPropertyChangeListener(preview);
choose.setFileSelectionMode(JFileChooser.FILES_ONLY);
String htmlExts[] = { "html", "htm" };
String imageExts[] = { "jpg", "jpeg", "png", "gif", "bmp" };
GenericFileFilter filter = new GenericFileFilter(htmlExts,
"HTML Files");
choose.addChoosableFileFilter(filter);
filter = new GenericFileFilter(imageExts,
"Images Files(*.jpg;*.jpeg;*.png;*.gif;*.bmp)");
choose.addChoosableFileFilter(filter);
choose.setFileView(new GenericFileView(imageExts));
/**//*
* addChoosableFileFilter(Filter filter) and
* setFileFilter(Filter filter) are two familiar
* methods,they both add the filter to the JFileChooser, the
* difference is the setFileFilter set itself to the default
* choose.
*/
int result = choose.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION){
File file = choose.getSelectedFile();
if (!file.exists())
area.append("File does not exist~!\n");
else
area.append("You chose " + file.getName() + "\n");
} else
return;
}
});
area = new JTextArea();
scroll = new JScrollPane(area);
Container cot = getContentPane();
cot.add(scroll, BorderLayout.CENTER);
panel = new JPanel();
panel.setLayout(new FlowLayout());
panel.add(btn1);
panel.add(btn2);
panel.add(btn3);
cot.add(panel, BorderLayout.NORTH);
setSize(400, 300);
setVisible(true);
}
public static void main(String args[]) {
FileChooserDemo app = new FileChooserDemo();
app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
class ImagePreviewPanel extends JPanel implements PropertyChangeListener {
private static final long serialVersionUID = 8127253177222723837L;
private ImageIcon icon;
private Image image;
private static final int ACCSIZE = 150;
private Color bg;
public ImagePreviewPanel() {
setPreferredSize(new Dimension(ACCSIZE, -1));
bg = getBackground();
}
public void propertyChange(PropertyChangeEvent e) {
String propertyName = e.getPropertyName();
if (propertyName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File selection = (File) e.getNewValue();
String name;
if (selection == null)
return;
else
name = selection.getAbsolutePath();
if ((name != null) && (name.toLowerCase().endsWith(".jpg")
|| name.toLowerCase().endsWith(".jpeg")
|| name.toLowerCase().endsWith(".gif")
|| name.toLowerCase().endsWith(".png"))) {
icon = new ImageIcon(name);
image = icon.getImage();
scaleImage();
repaint();
}
}
}
private void scaleImage() {
if (image.getWidth(this) >= image.getHeight(this)) {
image = image.getScaledInstance(ACCSIZE, -1, Image.SCALE_DEFAULT);
} else {
image = image.getScaledInstance(-1, ACCSIZE, Image.SCALE_DEFAULT);
}
}
public void paintComponent(Graphics g) {
g.setColor(bg);
/**//*
* If we don't do this, we will end up with garbage from previous
* images if they have larger sizes than the one we are currently
* drawing. Also, it seems that the file list can paint outside of
* its rectangle, and will cause odd behavior if we don't clear or
* fill the rectangle for the accessory before drawing. This might
* be a bug in JFileChooser.
*/
g.fillRect(0, 0, ACCSIZE, getHeight());
if(image!=null)
g.drawImage(image, getWidth() / 2 - image.getWidth(this) / 2, getHeight() / 2
- image.getHeight(this) / 2, this);
}
public static void main(String[] args) {
JFileChooser chooser = new JFileChooser();
ImagePreviewPanel preview = new ImagePreviewPanel();
chooser.setAccessory(preview);
chooser.addPropertyChangeListener(preview);
chooser.showOpenDialog(null);
}
}
class GenericFileFilter extends javax.swing.filechooser.FileFilter {
private static final boolean ONE = true;
private String fileExt;
private String[] fileExts;
private boolean type = false;
private String description;
private int length;
private String extension;
public GenericFileFilter(String[] filesExtsIn, String description) {
if (filesExtsIn.length == 1) {
type = ONE;
fileExt = filesExtsIn[0];
} else {
fileExts = filesExtsIn;
length = fileExts.length;
}
this.description = description;
}
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
extension = getExtension(f);
if (extension != null) {
if (type)
return check(fileExt);
else {
for (int i = 0; i < length; i++) {
if (check(fileExts[i]))
return true;
}
}
}
return false;
}
private boolean check(String in) {
return extension.equalsIgnoreCase(in);
}
public String getDescription() {
return description;
}
private String getExtension(File file) {
String filename = file.getName();
int length = filename.length();
int i = filename.lastIndexOf('.');
if (i > 0 && i < length - 1)
return filename.substring(i + 1).toLowerCase();
return null;
}
}
class GenericFileView extends FileView {
private String[] fileExts;
private String ext;
public GenericFileView(String[] fileExts) {
if (fileExts.length >= 1) {
this.fileExts = fileExts;
}
}
public Icon getIcon(File f) {
ext = getExtension(f);
if (ext.equals("") || ext.equals("lnk")) {
FileSystemView sv = FileSystemView.getFileSystemView();
if (sv != null)
return sv.getSystemIcon(f);
return super.getIcon(f);
}
return getImageIcon(f);
}
private Icon getImageIcon(File f) {
ImageIcon icon;
for (int i = 0; i < fileExts.length; i++) {
if (ext.equalsIgnoreCase(fileExts[i])) {
icon = new ImageIcon(f.getAbsolutePath());
Image image = icon.getImage();
if(icon.getIconHeight()>icon.getIconWidth())
image = image.getScaledInstance(-1, 50, Image.SCALE_DEFAULT);
else
image = image.getScaledInstance(50, -1, Image.SCALE_DEFAULT);
icon = new ImageIcon(image);
return icon;
}
}
return super.getIcon(f);
}
private String getExtension(File file) {
String filename = file.getName();
int length = filename.length();
int i = filename.lastIndexOf('.');
if (i > 0 && i < length - 1)
return filename.substring(i + 1).toLowerCase();
return new String("");
}
}