[JAVA100例]017、文件对话框
时间:2011-01-09
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.*;
/**
* <p>Title: 文件过滤器演示</p>
* <p>Description: FileChooserDemo文件使用的文件过滤器</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: MyFilter.java</p>
* @version 1.0
*/
public class MyFilter extends FileFilter {
private String files;
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null) {
if (extension.equals("java")) {//定义过滤Java文件
return true;
} else {
return false;
}
}
return false;
}
//过滤器描述
public String getDescription() {
return "Java";
}
/**
*<br>方法说明:获取文件扩展名
*<br>输入参数:
*<br>返回类型:
*/
public static String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf(´.´);
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i+1).toLowerCase();
}
return ext;
}
}
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.filechooser.*;
/**
* <p>Title: 文件对话框演示</p>
* <p>Description: 演示打开文件对话框和保存文件对话框,使用了文件过滤。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: FileChooserDemo.java</p>
* @version 1.0
*/
public class FileChooserDemo extends JPanel
implements ActionListener {
static private final String newline = "\n";
JButton openButton, saveButton;
JTextArea log;
JFileChooser fc;
public FileChooserDemo() {
super(new BorderLayout());
log = new JTextArea(15,40);
log.setMargin(new Insets(10,10,10,10));
log.setEditable(false);
JScrollPane logScrollPane = new JScrollPane(log);
//创建一个文件过滤,使用当前目录
fc = new JFileChooser(".");
//过滤条件在MyFilter类中定义
fc.addChoosableFileFilter(new MyFilter());
openButton = new JButton("打开文件",
createImageIcon("images/Open16.gif"));
openButton.addActionListener(this);
saveButton = new JButton("保存文件",
createImageIcon("images/Save16.gif"));
saveButton.addActionListener(this);
//构建一个面板,添加“打开文件”和“保存文件”
JPanel buttonPanel = new JPanel();
buttonPanel.add(openButton);
buttonPanel.add(saveButton);
add(buttonPanel, BorderLayout.PAGE_START);
add(logScrollPane, BorderLayout.CENTER);
}
/**
*<br>方法说明:事件处理
*<br>输入参数:
*<br>返回类型:
|