Fork me on GitHub

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

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()
          返回选中的文件。

button.addActionListener(new ActionListener() {        
public void actionPerformed(ActionEvent e) {  //按钮点击事件   
JFileChooser chooser new JFileChooser();             //设置选择器  
 chooser.setMultiSelectionEnabled(true);             //设为多选  
int returnVal = chooser.showOpenDialog(button);        //是否打开文件选择框  
System.out.println("returnVal="+returnVal);  
  
if (returnVal == JFileChooser.APPROVE_OPTION) {          //如果符合文件类型  
  
String filepath = chooser.getSelectedFile().getAbsolutePath();      //获取绝对路径  
System.out.println(filepath);  
System.out.println("You chose to open this file: "+ chooser.getSelectedFile().getName());  //输出相对路径  
}  
}  
});  

 

posted @ 2017-05-08 17:34  RongT  阅读(4581)  评论(0编辑  收藏  举报