JFileChooser()
构造一个指向用户默认目录的 JFileChooser。
JFileChooser(File currentDirectory)
设置 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[])。
构造一个指向用户默认目录的 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()
返回选中的文件。
代码:
- package com.liang;
- 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;
- 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);
- }
- @Override
- public void actionPerformed(ActionEvent e) {
- // TODO Auto-generated method stub
- JFileChooser jfc=new JFileChooser();
- jfc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
- jfc.showDialog(new JLabel(), "选择");
- File file=jfc.getSelectedFile();
- if(file.isDirectory()){
- System.out.println("文件夹:"+file.getAbsolutePath());
- }else if(file.isFile()){
- System.out.println("文件:"+file.getAbsolutePath());
- }
- System.out.println(jfc.getSelectedFile().getName());
- }
- }
JFileChooser 效果图如下: