import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.File;
import javax.swing.filechooser.FileFilter;
//文件选择器演示
public class Test extends JFrame {
private static final long serialVersionUID = 1L;
private JFileChooser chooser; //文件选择器
private JButton button; //选择文件按钮
private JComboBox comboBox; //用于设定文件对话框作用(打开还是保存文件)
public Test() {
super("JFileChooser 演示"); //调用父类构造函数
Container contentPane = getContentPane(); //得到容器
contentPane.setLayout(new FlowLayout()); //设置布局管理器为Flowlayout
chooser=new JFileChooser(); //初始化文件选择器
button = new JButton("选择文件"); //初始化按钮
comboBox=new JComboBox(); //初始化组合框
comboBox.addItem("保存");
contentPane.add(comboBox); //增加组件到容器
contentPane.add(button);
button.addActionListener(new ActionListener() { //按钮事件处理
public void actionPerformed(ActionEvent e) {
int state; //文件选择器返回状态
chooser.removeChoosableFileFilter(chooser.getAcceptAllFileFilter()); //移去所有文件过滤器
FileFilter type =
new MyFileFilter("图像文件", new String[] {
".jpg", ".gif", "jpeg"});//图形文件类别
chooser.addChoosableFileFilter(type); //增加文件过滤器,多图形文件过滤
state=chooser.showSaveDialog(null); //显示保存文件对话框
File file = chooser.getSelectedFile(); //得到选择的文件
if(file != null && state == JFileChooser.APPROVE_OPTION) { //选择了文件并点击了打开可保存按钮
JOptionPane.showMessageDialog(null, file.getPath()); //显示提示信息
}
else if(state == JFileChooser.CANCEL_OPTION) { //点击了撤销按钮
JOptionPane.showMessageDialog(null, "退出!"); //显示提示信息
}
else if(state == JFileChooser.ERROR_OPTION) {
JOptionPane.showMessageDialog(null, "错误!"); //显示提示信息
}
}
});
this.setSize(200,100); //设置窗口大小
this.setVisible(true); //设置窗口可见
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时退出程序
}
public static void main(String args[]) {
new Test();
}
}
//文件过滤器
class MyFileFilter extends FileFilter {
String ends[]; //文件后缀
String description; //文件描述文字
public MyFileFilter(String ends, String description) { //构造函数
this(description, new String[] {ends});
}
public MyFileFilter(String description, String ends[]){
this.description = description;
this.ends = (String[])ends.clone();
}
public boolean accept(File file) { //重载FileFilter中的accept方法
if (file.isDirectory()) //如果是目录,则返回true
return true;
int count = ends.length;//获取图片文件类型数
String path = file.getName();//获取文件名
for(int i = 0; i < count; i++){
String ext = ends[i];
if(path.toUpperCase().endsWith(ext.toUpperCase()))//判断图片类型是否相符
{
return true;
}}
return false;
}
public String getDescription() { //返回文件描述文字
return (description == null ?ends[0] : description);
}
}
//参考两个例子后,自己改了一个,终于可以满足项目使用要求了.