Java_java中JFileChooser类(java_swing提供的文件选择对话框)

来源:互联网 发布:2016中国人工智能大会 编辑:程序博客网 时间:2024/05/01 04:22
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.   
  3. import java.awt.event.ActionEvent;  
  4. import java.awt.event.ActionListener;  
  5. import java.io.File;  
  6.   
  7. import javax.swing.JButton;  
  8. import javax.swing.JFileChooser;  
  9. import javax.swing.JFrame;  
  10. import javax.swing.JLabel;  
  11.   
  12. public class FileChooser extends JFrame implements ActionListener{  
  13.     JButton open=null;  
  14.     public static void main(String[] args) {  
  15.         new FileChooser();  
  16.     }  
  17.     public FileChooser(){  
  18.         open=new JButton("open");  
  19.         this.add(open);  
  20.         this.setBounds(400200100100);  
  21.         this.setVisible(true);  
  22.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  23.         open.addActionListener(this);  
  24.     }  
  25.     @Override  
  26.     public void actionPerformed(ActionEvent e) {  
  27.         // TODO Auto-generated method stub  
  28.         JFileChooser jfc=new JFileChooser();  
  29.         jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );  
  30.         jfc.showDialog(new JLabel(), "选择");  
  31.         File file=jfc.getSelectedFile();  
  32.         if(file.isDirectory()){  
  33.             System.out.println("文件夹:"+file.getAbsolutePath());  
  34.         }else if(file.isFile()){  
  35.             System.out.println("文件:"+file.getAbsolutePath());  
  36.         }  
  37.         System.out.println(jfc.getSelectedFile().getName());  
  38.           
  39.     }  
  40.   
  41. }  

JFileChooser 效果图如下:





0 0