源代码:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTable;
public class FileChooser extends JFrame implements ActionListener{
JButton open=null;
public static void main(String[] args){
new FileChooser();
}
public FileChooser(){
open=new JButton("open");
this.add(open);
this.setBounds(400,200,100,100);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
open.addActionListener(this);
}
public void actionPerformed(ActionEvent e){
//TODO Auto-generated method stub
JFileChooser jfc=new JFileChooser();
jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
jfc.showDialog(new JTable(),"选择");
File file=jfc.getSelectedFile();
if(file.isDirectory()){
System.out.println("文件夹:"+file.getAbsolutePath());
}else if(file.isFile()){
System.out.println("文件夹:"+getAbsolutePath());
}
System.out.println(jfc.getSelectedFile().getName());
}
private String getAbsolutePath() {
// TODO Auto-generated method stub
return null;
}
}
运行结果:
<img src="https://img-blog.youkuaiyun.com/20150625231239389?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzkyODUzOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
<img src="https://img-blog.youkuaiyun.com/20150625231327223?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMzkyODUzOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />