JFileChooser (Java Swing提供的文件选择对话框)

JFileChooser()
          构造一个指向用户默认目录的 JFileChooser
JFileChooser(File currentDirectory)
          使用给定的 File 作为路径来构造一个 JFileChooser

setFileSelectionMode(int mode)
          设置 JFileChooser,以允许用户只选择文件、只选择目录,或者可选择文件和目录。

mode参数:FILES_AND_DIRECTORIES   指示显示文件和目录。

      FILES_ONLY                             指示仅显示文件。

     DIRECTORIES_ONLY                指示仅显示目录。

showDialog(Component parent,String approveButtonText)
          弹出具有自定义 approve 按钮的自定义文件选择器对话框。

showOpenDialog(Component parent)
          弹出一个 "Open File" 文件选择器对话框。

showSaveDialog(Component parent)
          弹出一个 "Save File" 文件选择器对话框。

setMultiSelectionEnabled(boolean b)
          设置文件选择器,以允许选择多个文件。

getSelectedFiles() 
          如果将文件选择器设置为允许选择多个文件,则返回选中文件的列表(File[])。

getSelectedFile()
          返回选中的文件。


  1. package com.liang;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.io.File;
  5. import javax.swing.JButton;
  6. import javax.swing.JFileChooser;
  7. import javax.swing.JFrame;
  8. import javax.swing.JLabel;
  9. public class FileChooser extends JFrame implements ActionListener{
  10. JButton open=null;
  11. public static void main(String[] args) {
  12. new FileChooser();
  13. }
  14. public FileChooser(){
  15. open=new JButton("open");
  16. this.add(open);
  17. this.setBounds(400, 200, 100, 100);
  18. this.setVisible(true);
  19. this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  20. open.addActionListener(this);
  21. }
  22. @Override
  23. public void actionPerformed(ActionEvent e) {
  24. // TODO Auto-generated method stub
  25. JFileChooser jfc=new JFileChooser();
  26. jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
  27. jfc.showDialog(new JLabel(), "选择");
  28. File file=jfc.getSelectedFile();
  29. if(file.isDirectory()){
  30. System.out.println("文件夹:"+file.getAbsolutePath());
  31. }else if(file.isFile()){
  32. System.out.println("文件:"+file.getAbsolutePath());
  33. }
  34. System.out.println(jfc.getSelectedFile().getName());
  35. }
  36. }


JFileChooser 效果图如下:

JFileChooser (Java Swing提供的文件选择对话框)