这位楼主写的bug还真隐蔽啊,不仔细一点还看不到.
new WindowAdapter的时候,应该override父类中的平庸实现的windowClosing方法,而程序中写成了WindowClosing,那当然你关闭事件的时候没有反应了.
把WindowClosing改成windowClosing就没有问题了.
new WindowAdapter的时候,应该override父类中的平庸实现的windowClosing方法,而程序中写成了WindowClosing,那当然你关闭事件的时候没有反应了.
把WindowClosing改成windowClosing就没有问题了.
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class JFileChooserDemo extends JPanel{
public JFileChooserDemo(JFrame f){
final JFrame frame = f;
final JFileChooser chooser = new JFileChooser();
JFileFilter filter = new JFileFilter();
filter.addType(".java");
filter.addType(".class");
filter.addType(".jar");
filter.setDescription("Java-related files");
chooser.addChoosableFileFilter(filter);
JButton b = new JButton("choose file");
add(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
int returnVal = chooser.showOpenDialog(frame);
if (returnVal == JFileChooser.APPROVE_OPTION){
System.out.println("You choose a file named: "+
chooser.getSelectedFile().getPath());
}else{
System.out.println("You did not choose a file");
}
}
});
}
class JFileFilter extends javax.swing.filechooser.FileFilter{
protected String description;
protected ArrayList exts = new ArrayList();
public void addType(String s){
exts.add(s);
}
public boolean accept(File f){
if (f.isDirectory())
{
return true;
}else if(f.isFile()){
Iterator it = exts.iterator();
while(it.hasNext()) {
if(f.getName().endsWith((String)it.next()))
return true;
}
}
return false;
}
public void setDescription(String s){
description = s;
}
public String getDescription(){
return description;
}
}
public static void main(String args[])
{
JFrame f = new JFrame("JFileChooser Demo");
f.getContentPane().add(new JFileChooserDemo(f));
f.pack();
f.setVisible(true);
/*************************************************/
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().setVisible(false);
e.getWindow().dispose();
System.exit(0);
}
});
/*************************************************/
}
}