FileDialog文件名过滤问题
请问:
FileDialog文件过滤应该怎么做呢?
我是这样写的,
做了一个类实现了FilenameFilter接口,在accept函数中进行了判断。
在用文件对话框的事例调用了SetFilenameFilter();方法,可是还是没有实现功能。
下面是我程序的部分代码:
class MyFrame extends Frame implements ActionListener,FilenameFilter{
MyMenuBar mnubar;
TextArea txtContext;
public MyFrame(String title) {
super(title);
mnubar = new MyMenuBar();
this.setMenuBar(mnubar);
mnubar.mnuSysClose.addActionListener(this);
mnubar.mnuSysOpen.addActionListener(this);
mnubar.mnuSysSave.addActionListener(this);
txtContext = new TextArea();
this.add(BorderLayout.CENTER, txtContext);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==mnubar.mnuSysClose) {
if(JOptionPane.YES_OPTION==JOptionPane.showConfirmDialog(null,"您真的要退出吗?","提示",JOptionPane.YES_NO_OPTION)) {
System.exit(0);
}
}
else if(e.getSource()==mnubar.mnuSysOpen) {
FileDialog dlg = new FileDialog(this,"打开文件",FileDialog.LOAD);
dlg.setFilenameFilter(this);
dlg.setVisible(true);
String file = dlg.getFile();
String directory = dlg.getDirectory();
try {
loadText(new File(directory,file));
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
else if(e.getSource()==mnubar.mnuSysSave) {
FileDialog dlg = new FileDialog(this,"保存文件",FileDialog.SAVE);
dlg.setVisible(true);
try {
saveText(new File(dlg.getDirectory(),dlg.getFile()));
}
catch(Exception ex) {
System.out.println(ex.getMessage());
}
}
}
public boolean accept(File dir,String name) {
int len = name.length();
System.out.println(name);
if(name.toLowerCase().substring(len-4, len-1).equals("txt"))
return true;
return false;
}
public void loadText(File file) throws Exception {
txtContext.setText("");
FileReader fr = new FileReader(file);
BufferedReader br= new BufferedReader(fr);
String s;
while((s=br.readLine())!=null) {
txtContext.append(s+"\n");
}
mnubar.refresh();
br.close();
}
public void saveText(File file) throws Exception {
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(txtContext.getText());
bw.flush();
bw.close();
}
}