请java api
这是我在API中找到的帮助内容
但是不知道怎么用ExampleFileFilter这个类根本不存在
如果自己写这个类的话我又不知道写什么
以下代码弹出一个针对用户主目录的文件选择器,其中只显示 .jpg 和 .gif 图像:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the JDK.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension("jpg");
filter.addExtension("gif");
filter.setDescription("JPG & GIF Images");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
[CODE]import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.io.*;
public class OpenFileTester extends JFrame implements ActionListener{
private JMenuBar jMenuBar;
private JMenu jMenu;
private JMenuItem jMenuItem;
public OpenFileTester(){
jMenuBar=new JMenuBar();
jMenu=new JMenu("文件");
jMenuItem=new JMenuItem("打开");
jMenuItem.addActionListener(this);
jMenu.add(jMenuItem);
jMenuBar.add(jMenu);
setTitle("JFileChooser Demo");
setJMenuBar(jMenuBar);
setSize(new Dimension(300,200));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e){
try{
JFileChooser jf=new JFileChooser();
jf.addChoosableFileFilter(new OFileFilter(".exe","exe文件"));
jf.addChoosableFileFilter(new OFileFilter(".txt","txt文件"));
int result=jf.showOpenDialog(null);
}catch(Exception ex){
ex.printStackTrace();
}
}
public static void main(String[] args){
new OpenFileTester().setVisible(true);
}
}
/*
*类OFileFilter继承自FileFilter抽象类,用以在JFileChooser类中实现文件过滤器
*/
class OFileFilter extends javax.swing.filechooser.FileFilter{
private String strEnds;
private String strDescription;
public OFileFilter(String strEnds,String strDescription){
this.strEnds=strEnds;
this.strDescription=strDescription;
}
public boolean accept(File file){
if(file.isDirectory()) return true;
String filename=file.getAbsolutePath();
if(filename.toUpperCase().endsWith(strEnds.toUpperCase())){
return true;
}else{
return false;
}
}
public String getDescription(){
return this.strDescription;
}
}[/CODE]