Documentation

The Java™ Tutorials
Hide TOC
How to Use File Choosers如何使用文件选择器
Trail: Creating a GUI With Swing
Lesson: Using Swing Components
Section: How to Use Various Components

How to Use File Choosers如何使用文件选择器

File choosers provide a GUI for navigating the file system, and then either choosing a file or directory from a list, or entering the name of a file or directory. 文件选择器提供了一个GUI,用于导航文件系统,然后从列表中选择文件或目录,或者输入文件或目录的名称。To display a file chooser, you usually use the JFileChooser API to show a modal dialog containing the file chooser. 要显示文件选择器,通常使用JFileChooser API来显示包含文件选择器的模式对话框Another way to present a file chooser is to add an instance of JFileChooser to a container.呈现文件选择器的另一种方法是将JFileChooser的实例添加到容器中。


Note: 

If you intend to distribute your program as a sandbox Java Web Start application, then instead of using the JFileChooser API you should use the file services provided by the JNLP API. 如果您打算将程序作为沙盒Java Web Start应用程序分发,那么您应该使用JNLP API提供的文件服务,而不是使用JFileChooser API。These services — FileOpenService and FileSaveService — not only provide support for choosing files in a restricted environment, but also take care of actually opening and saving them. 这些服务—FileOpenServiceFileSaveService—不仅支持在受限环境中选择文件,而且还负责实际打开和保存文件。An example of using these services is in JWSFileChooserDemo. JWSFileChooserDemo中有一个使用这些服务的示例。Documentation for using the JNLP API can be found in the Java Web Start lesson.使用JNLPAPI的文档可以在Java Web Start课程中找到。


Click the Launch button to run JWSFileChooserDemo using Java™ Web Start (download JDK 7 or later). 单击启动按钮,使用Java™Web启动运行JWSFileChooserDemo(下载JDK 7或更高版本)。Alternatively, to compile and run the example yourself, consult the example index.或者,要自己编译和运行示例,请参考示例索引

Launches the JWSFileChooserDemo application

When working with the JWSFileChooserDemo example, be careful not to lose files that you need. 使用JWSFileChooserDemo示例时,请注意不要丢失所需的文件。Whenever you click the save button and select an existing file, this demo brings up the File Exists dialog box with a request to replace the file. 每当您单击“保存”按钮并选择现有文件时,此演示将打开“文件存在”对话框,并请求替换该文件。Accepting the request overwrites the file.接受请求将覆盖文件。

The rest of this section discusses how to use the JFileChooser API. 本节其余部分讨论如何使用JFileChooser API。A JFileChooser object only presents the GUI for choosing files. JFileChooser对象仅显示用于选择文件的GUI。Your program is responsible for doing something with the chosen file, such as opening or saving it. 您的程序负责对所选文件执行某些操作,例如打开或保存文件。Refer to Basic I/O for information on how to read and write files.有关如何读取和写入文件的信息,请参阅基本I/O

The JFileChooser API makes it easy to bring up open and save dialogs. JFileChooser API使打开和保存对话框变得容易。The type of look and feel determines what these standard dialogs look like and how they differ. 外观类型决定了这些标准对话框的外观以及它们之间的区别。In the Java look and feel, the save dialog looks the same as the open dialog, except for the title on the dialog's window and the text on the button that approves the operation. 在Java外观中,除了对话框窗口上的标题和批准操作的按钮上的文本外,“保存”对话框与“打开”对话框的外观相同。Here is a picture of a standard open dialog in the Java look and feel:以下是Java外观中标准打开对话框的图片:

A standard open dialog shown in the Java look and feel

Here is a picture of an application called FileChooserDemo that brings up an open dialog and a save dialog.下面是一个名为FileChooserDemo的应用程序的图片,该应用程序将打开一个打开对话框和一个保存对话框。

A program that brings up an open or save dialog

Try this: 
  1. Compile and run the example, consult the example index.编译并运行示例,请参考示例索引
  2. Click the Open a File button. 单击“打开文件”按钮。Navigate around the file chooser, choose a file, and click the dialog's Open button.在文件选择器周围导航,选择一个文件,然后单击对话框的“打开”按钮。
  3. Use the Save a File button to bring up a save dialog. 使用“保存文件”按钮打开保存对话框。Try to use all of the controls on the file chooser.尝试使用文件选择器上的所有控件。
  4. In the source file FileChooserDemo.java, change the file selection mode to directories-only mode. 在源文件FileChooserDemo.java中,将文件选择模式更改为仅目录模式。(Search for DIRECTORIES_ONLY and uncomment the line that contains it.) (搜索DIRECTORIES_ONLY并取消对包含它的行的注释。)Then compile and run the example again. 然后编译并再次运行该示例。You will only be able to see and select directories, not ordinary files.您将只能查看和选择目录,而不是普通文件。

Bringing up a standard open dialog requires only two lines of code:打开标准打开对话框只需要两行代码:

//Create a file chooser
final JFileChooser fc = new JFileChooser();
...
//In response to a button click:
int returnVal = fc.showOpenDialog(aComponent);

The argument to the showOpenDialog method specifies the parent component for the dialog. showOpenDialog方法的参数指定对话框的父组件。The parent component affects the position of the dialog and the frame that the dialog depends on. 父组件影响对话框的位置和对话框所依赖的框架。For example, the Java look and feel places the dialog directly over the parent component. 例如,Java外观将对话框直接放置在父组件上。If the parent component is in a frame, then the dialog is dependent on that frame. 如果父零部件位于框架中,则对话框依赖于该框架。This dialog disappears when the frame is minimized and reappears when the frame is maximized.当框架最小化时,此对话框消失,当框架最大化时,该对话框重新出现。

By default, a file chooser that has not been shown before displays all files in the user's home directory. 默认情况下,以前未显示的文件选择器将显示用户主目录中的所有文件。You can specify the file chooser's initial directory by using one of JFileChooser's other constructors, or you can set the directory with the setCurrentDirectory method.您可以使用JFileChooser的其他构造函数之一指定文件选择器的初始目录,也可以使用setCurrentDirectory方法设置目录。

The call to showOpenDialog appears in the actionPerformed method of the Open a File button's action listener:showOpenDialog的调用出现在“打开文件”按钮的操作侦听器的actionPerformed方法中:

public void actionPerformed(ActionEvent e) {
    //Handle open button action.
    if (e.getSource() == openButton) {
        int returnVal = fc.showOpenDialog(FileChooserDemo.this);

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            log.append("Opening: " + file.getName() + "." + newline);
        } else {
            log.append("Open command cancelled by user." + newline);
        }
   } ...
}

The showXxxDialog methods return an integer that indicates whether the user selected a file. showXxxDialog方法返回一个整数,指示用户是否选择了文件。Depending on how you use a file chooser, it is often sufficient to check whether the return value is APPROVE_OPTION and then not to change any other value. 根据您使用文件选择器的方式,检查返回值是否为APPROVE_OPTION,然后不更改任何其他值通常就足够了。To get the chosen file (or directory, if you set up the file chooser to allow directory selections), call the getSelectedFile method on the file chooser. 要获取所选文件(或目录,如果将文件选择器设置为允许目录选择),请在文件选择器上调用getSelectedFile方法。This method returns an instance of File.此方法返回File的实例。

The example obtains the name of the file and uses it in the log message. 该示例获取文件名并在日志消息中使用它。You can call other methods on the File object, such as getPath, isDirectory, or exists to obtain information about the file. 您可以调用File对象上的其他方法,如getPathisDirectoryexists,以获取有关文件的信息。You can also call other methods such as delete and rename to change the file in some way. 您还可以调用其他方法,如deleterename,以某种方式更改文件。Of course, you might also want to open or save the file by using one of the reader or writer classes provided by the Java platform. 当然,您可能还希望使用Java平台提供的读写器类打开或保存文件。See Basic I/O for information about using readers and writers to read and write data to the file system.有关使用读写器向文件系统读写数据的信息,请参阅基本I/O

The example program uses the same instance of the JFileChooser class to display a standard save dialog. 示例程序使用JFileChooser类的相同实例来显示标准保存对话框。This time the program calls showSaveDialog:这次程序调用showSaveDialog

int returnVal = fc.showSaveDialog(FileChooserDemo.this);

By using the same file chooser instance to display its open and save dialogs, the program reaps the following benefits:通过使用相同的文件选择器实例来显示其打开和保存对话框,该程序获得了以下好处:

Finally, the example program has commented-out lines of code that let you change the file selection mode. 最后,示例程序注释掉了允许您更改文件选择模式的代码行。For example, the following line of code makes the file chooser able to select only directories, and not files:例如,以下代码行使文件选择器只能选择目录,而不能选择文件:

fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

Another possible selection mode is FILES_AND_DIRECTORIES. 另一种可能的选择模式是FILES_AND_DIRECTORIESThe default is FILES_ONLY. 默认值为FILES_ONLYThe following picture shows an open dialog with the file selection mode set to DIRECTORIES_ONLY. 下图显示了一个打开的对话框,其中文件选择模式设置为DIRECTORIES_ONLYNote that, in the Java look and feel at least, only directories are visible — not files.请注意,至少在Java外观中,只有目录是可见的;不是文件。

A file chooser in DIRECTORIES_ONLY mode

If you want to create a file chooser for a task other than opening or saving, or if you want to customize the file chooser, keep reading. 如果要为打开或保存以外的任务创建文件选择器,或者要自定义文件选择器,请继续阅读。We will discuss the following topics:我们将讨论以下主题:

Another Example: 另一个例子:FileChooserDemo2

Let us look at FileChooserDemo2 example, a modified version of the previous demo program that uses more of the JFileChooser API. 让我们看看FileChooserDemo2示例,它是先前演示程序的修改版本,使用了更多的JFileChooser API。This example uses a file chooser that has been customized in several ways. 本示例使用了一个已通过多种方式自定义的文件选择器。Like the original example, the user invokes a file chooser with the push of a button. Here is a picture of the file chooser:与原始示例一样,用户只需按下按钮即可调用文件选择器。以下是文件选择器的图片:

A file chooser with various customizations

As the figure shows, this file chooser has been customized for a special task (Attach), provides a user-choosable file filter (Just Images), uses a special file view for image files, and has an accessory component that displays a thumbnail sketch of the currently selected image file.如图所示,此文件选择器已针对特殊任务(附加)进行了自定义,提供了用户可选择的文件筛选器(仅图像),为图像文件使用特殊的文件视图,并具有显示当前选定图像文件的缩略图草图的附件组件。

The remainder of this section shows you the code that creates and customizes this file chooser. 本节的其余部分将显示创建和自定义此文件选择器的代码。See the example index for links to all the files required by this example.有关此示例所需的所有文件的链接,请参阅示例索引

Using a File Chooser for a Custom Task为自定义任务使用文件选择器

As you have seen, the JFileChooser class provides the showOpenDialog method for displaying an open dialog and the showSaveDialog method for displaying a save dialog.如您所见,JFileChooser类提供了用于显示打开对话框的showOpenDialog方法和用于显示保存对话框的showSaveDialog方法。

The class has another method, showDialog, for displaying a file chooser for a custom task in a dialog. 该类还有另一个方法showDialog,用于在对话框中显示自定义任务的文件选择器。In the Java look and feel, the only difference between this dialog and the other file chooser dialogs is the title on the dialog window and the label on the approve button. 在Java外观中,此对话框与其他文件选择器对话框之间的唯一区别是对话框窗口上的标题和批准按钮上的标签。Here is the code from FileChooserDemo2 that brings up the file chooser dialog for the Attach task:以下是FileChooserDemo2中的代码,它为附加任务打开了文件选择器对话框:

JFileChooser fc = new JFileChooser();
int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");

The first argument to the showDialog method is the parent component for the dialog. showDialog方法的第一个参数是对话框的父组件。The second argument is a String object that provides both the title for the dialog window and the label for the approve button.第二个参数是一个String对象,它提供对话框窗口的标题和批准按钮的标签。

Once again, the file chooser doesn't do anything with the selected file. 同样,文件选择器不会对所选文件执行任何操作。The program is responsible for implementing the custom task for which the file chooser was created.该程序负责实现为其创建文件选择器的自定义任务。

Filtering the List of Files筛选文件列表

By default, a file chooser displays all of the files and directories that it detects, except for hidden files. 默认情况下,文件选择器显示其检测到的所有文件和目录,但隐藏文件除外。A program can apply one or more file filters to a file chooser so that the chooser shows only some files. 程序可以将一个或多个文件筛选器应用于文件选择器,以便选择器仅显示一些文件。The file chooser calls the filter's accept method for each file to determine whether it should be displayed. 文件选择器为每个文件调用筛选器的accept方法,以确定是否应显示该文件。A file filter accepts or rejects a file based on criteria such as file type, size, ownership, and so on. 文件筛选器根据文件类型、大小、所有权等条件接受或拒绝文件。Filters affect the list of files displayed by the file chooser. 筛选器影响文件选择器显示的文件列表。The user can enter the name of any file even if it is not displayed.用户可以输入任何文件的名称,即使该文件未显示。

JFileChooser supports three different kinds of filtering. 支持三种不同类型的筛选。The filters are checked in the order listed here. 按此处列出的顺序检查筛选器。For example, an application-controlled filter sees only those files accepted by the built-in filtering.例如,应用程序控制的筛选器仅查看内置筛选接受的文件。

Built-in filtering内置筛选
Filtering is set up through specific method calls on a file chooser. 筛选是通过文件选择器上的特定方法调用来设置的。Currently the only built-in filter available is for hidden files, such as those whose names begin with period (.) on UNIX systems. 目前,唯一可用的内置筛选器是用于隐藏文件,例如UNIX系统上名称以句点(.)开头的文件。By default, hidden files are not shown. 默认情况下,不显示隐藏文件。Call setFileHidingEnabled(false) to show hidden files.调用setFileHidingEnabled(false)以显示隐藏文件。
Application-controlled filtering控制筛选的应用
The application determines which files are shown. 应用程序确定显示哪些文件。Create a custom subclass of FileFilter, instantiate it, and use the instance as an argument to the setFileFilter method. 创建FileFilter的自定义子类,实例化它,并将该实例用作setFileFilter方法的参数。The installed filter is displayed on the list of user-choosable filters. 安装的筛选器显示在用户可选择的筛选器列表上。The file chooser shows only those files that the filter accepts.文件选择器仅显示筛选器接受的文件。
User-choosable filtering用户可选择筛选
The file chooser GUI provides a list of filters that the user can choose from. When the user chooses a filter, the file chooser shows only those files accepted by that filter. 文件选择器GUI提供了用户可以选择的筛选器列表。当用户选择筛选器时,文件选择器仅显示该筛选器接受的文件。FileChooserDemo2 adds a custom file filter to the list of user-choosable filters:将自定义文件筛选器添加到用户可选择的筛选器列表中:
fc.addChoosableFileFilter(new ImageFilter());
By default, the list of user-choosable filters includes the Accept All filter, which enables the user to see all non-hidden files. 默认情况下,用户可选择的筛选器列表包括“全部接受”筛选器,该筛选器允许用户查看所有非隐藏文件。This example uses the following code to disable the Accept All filter:此示例使用以下代码禁用“全部接受”筛选器:
fc.setAcceptAllFileFilterUsed(false);
Our custom file filter is implemented in ImageFilter.java and is a subclass of FileFilter. 自定义文件筛选器在ImageFilter.java中实现,是FileFilter的一个子类。The ImageFilter class implements the getDescription method to return "Just Images" — a string to put in the list of user-choosable filters. ImageFilter类实现getDescription方法以返回“仅图像”—要放入用户可选择筛选器列表中的字符串。ImageFilter also implements the accept method so that it accepts all directories and any file that has a .png, .jpg, .jpeg, .gif, .tif, or .tiff filename extension. ImageFilter还实现了accept方法,以便它接受所有目录和任何扩展名为.png.jpg.jpeg.gif.tif.tiff的文件。
public boolean accept(File f) {
    if (f.isDirectory()) {
        return true;
    }

    String extension = Utils.getExtension(f);
    if (extension != null) {
        if (extension.equals(Utils.tiff) ||
            extension.equals(Utils.tif) ||
            extension.equals(Utils.gif) ||
            extension.equals(Utils.jpeg) ||
            extension.equals(Utils.jpg) ||
            extension.equals(Utils.png)) {
                return true;
        } else {
            return false;
        }
    }

    return false;
}
By accepting all directories, this filter allows the user to navigate around the file system. 通过接受所有目录,此筛选器允许用户在文件系统中导航。If the bold lines were omitted from this method, the user would be limited to the directory with which the chooser was initialized. 如果此方法中省略了粗体行,则用户将被限制在初始化选择器的目录中。

The preceding code sample uses the getExtension method and several string constants from Utils.java, shown here:前面的代码示例使用了getExtension方法和Utils.java中的几个字符串常量,如下所示:

public class Utils {

    public final static String jpeg = "jpeg";
    public final static String jpg = "jpg";
    public final static String gif = "gif";
    public final static String tiff = "tiff";
    public final static String tif = "tif";
    public final static String png = "png";

    /*
     * Get the extension of a file.
     */  
    public static String getExtension(File f) {
        String ext = null;
        String s = f.getName();
        int i = s.lastIndexOf('.');

        if (i > 0 &&  i < s.length() - 1) {
            ext = s.substring(i+1).toLowerCase();
        }
        return ext;
    }
}

Customizing the File View自定义文件视图

In the Java look and feel, the chooser's list shows each file's name and displays a small icon that represents whether the file is a true file or a directory. 在Java外观中,选择器列表显示每个文件的名称,并显示一个小图标,表示该文件是真正的文件还是目录。You can customize this file view by creating a custom subclass of FileView and using an instance of the class as an argument to the setFileView method. 您可以通过创建FileView的自定义子类并使用该类的实例作为setFileView方法的参数来自定义此文件视图。The example uses an instance of a custom class, implemented in ImageFileView.java, as the file chooser's file view.该示例使用在ImageFileView.java中实现的自定义类的实例作为文件选择器的文件视图。

fc.setFileView(new ImageFileView());

The ImageFileView class shows a different icon for each type of image accepted by the image filter described previously.ImageFileView类为前面描述的图像筛选器接受的每种类型的图像显示不同的图标。

The ImageFileView class overrides the five abstract methods defined in the FileView as follows.ImageFileView类重写FileView中定义的五个抽象方法,如下所示。

String getTypeDescription(File f)
Returns a description of the file type. 返回文件类型的描述。Here is ImageFileView's implementation of this method:下面是ImageFileView对该方法的实现:
public String getTypeDescription(File f) {
    String extension = Utils.getExtension(f);
    String type = null;

    if (extension != null) {
        if (extension.equals(Utils.jpeg) ||
            extension.equals(Utils.jpg)) {
            type = "JPEG Image";
        } else if (extension.equals(Utils.gif)){
            type = "GIF Image";
        } else if (extension.equals(Utils.tiff) ||
                   extension.equals(Utils.tif)) {
            type = "TIFF Image";
        } else if (extension.equals(Utils.png)){
            type = "PNG Image";
        }
    }
    return type;
}
Icon getIcon(File f)
Returns an icon representing the file or its type. 返回表示文件或其类型的图标。Here is ImageFileView's implementation of this method:下面是ImageFileView对该方法的实现:
public Icon getIcon(File f) {
    String extension = Utils.getExtension(f);
    Icon icon = null;

    if (extension != null) {
        if (extension.equals(Utils.jpeg) ||
            extension.equals(Utils.jpg)) {
            icon = jpgIcon;
        } else if (extension.equals(Utils.gif)) {
            icon = gifIcon;
        } else if (extension.equals(Utils.tiff) ||
                   extension.equals(Utils.tif)) {
            icon = tiffIcon;
        } else if (extension.equals(Utils.png)) {
            icon = pngIcon;
        }
    }
    return icon;
}
String getName(File f)
Returns the name of the file. 返回文件的名称。Most implementations of this method should return null to indicate that the look and feel should figure it out. 此方法的大多数实现都应该返回null,以表明外观应该能够解决这个问题。Another common implementation returns f.getName().另一个常见的实现返回f.getName()
String getDescription(File f)
Returns a description of the file. 返回文件的描述。The intent is to describe individual files more specifically. 其目的是更具体地描述各个文件。A common implementation of this method returns null to indicate that the look and feel should figure it out.此方法的一个常见实现返回null,以指示外观应该能够解决此问题。
Boolean isTraversable(File f)
Returns whether a directory is traversable. 返回目录是否可遍历。Most implementations of this method should return null to indicate that the look and feel should figure it out. 此方法的大多数实现都应该返回null,以表明外观应该能够解决这个问题。Some applications might want to prevent users from descending into a certain type of directory because it represents a compound document. 某些应用程序可能希望阻止用户下降到特定类型的目录中,因为它表示复合文档。The isTraversable method should never return true for a non-directory.对于非目录,isTraversable方法不应返回true

Providing an Accessory Component提供附件组件

The customized file chooser in FileChooserDemo2 has an accessory component. FileChooserDemo2中的自定义文件选择器具有附件组件。If the currently selected item is a PNG, JPEG, TIFF, or GIF image, the accessory component displays a thumbnail sketch of the image. 如果当前选定的项目是PNG、JPEG、TIFF或GIF图像,则附件组件将显示图像的缩略图草图。Otherwise, the accessory component is empty. 否则,附件部件为空。Aside from a previewer, probably the most common use for the accessory component is a panel with more controls on it such as check boxes that toggle between features.除了预览器,附件组件最常见的用途可能是面板,面板上有更多控件,例如在功能之间切换的复选框。

The example calls the setAccessory method to establish an instance of the ImagePreview class, implemented in ImagePreview.java, as the chooser's accessory component:该示例调用setAccessory方法来建立ImagePreview类的实例,该类在ImagePreview.java中实现,作为选择器的附件组件:

fc.setAccessory(new ImagePreview(fc));

Any object that inherits from the JComponent class can be an accessory component. JComponent类继承的任何对象都可以是附件组件。The component should have a preferred size that looks good in the file chooser.组件应具有在文件选择器中看起来良好的首选大小。

The file chooser fires a property change event when the user selects an item in the list. 当用户选择列表中的项目时,文件选择器将触发属性更改事件。A program with an accessory component must register to receive these events to update the accessory component whenever the selection changes. 带有附件组件的程序必须注册以接收这些事件,以便在选择更改时更新附件组件。In the example, the ImagePreview object itself registers for these events. 在本例中,ImagePreview对象本身为这些事件注册。This keeps all the code related to the accessory component together in one class.这将与附件组件相关的所有代码保持在一个类中。

Here is the example's implementation of the propertyChange method, which is the method called when a property change event is fired:以下是propertyChange方法的示例实现,该方法是在触发属性更改事件时调用的方法:

//where member variables are declared
File file = null;
...
public void propertyChange(PropertyChangeEvent e) {
    boolean update = false;
    String prop = e.getPropertyName();

    //If the directory changed, don't show an image.
    if (JFileChooser.DIRECTORY_CHANGED_PROPERTY.equals(prop)) {
        file = null;
        update = true;

    //If a file became selected, find out which one.
    } else if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
        file = (File) e.getNewValue();
        update = true;
    }

    //Update the preview accordingly.
    if (update) {
        thumbnail = null;
        if (isShowing()) {
            loadImage();
            repaint();
        }
    }
}

If SELECTED_FILE_CHANGED_PROPERTY is the property that changed, this method obtains a File object from the file chooser. 如果SELECTED_FILE_CHANGED_PROPERTY是已更改的属性,则此方法从文件选择器获取File对象。The loadImage and repaint methods use the File object to load the image and repaint the accessory component.loadImagerepaint方法使用File对象加载图像并重新绘制附件组件。

The File Chooser API文件选择器API

The API for using file choosers falls into these categories:使用文件选择器的API分为以下几类:

Creating and Showing the File Chooser创建和显示文件选择器
Method or Constructor方法或构造函数 Purpose目的
JFileChooser()
JFileChooser(File)
JFileChooser(String)
Creates a file chooser instance. 创建文件选择器实例。The File and String arguments, when present, provide the initial directory.FileString参数(如果存在)提供初始目录。
int showOpenDialog(Component)
int showSaveDialog(Component)
int showDialog(Component, String)
Shows a modal dialog containing the file chooser. 显示包含文件选择器的模式对话框。These methods return APPROVE_OPTION if the user approved the operation and CANCEL_OPTION if the user cancelled it. 如果用户批准操作,则这些方法返回APPROVE_OPTION,如果用户取消操作,则返回CANCEL_OPTIONAnother possible return value is ERROR_OPTION, which means an unanticipated error occurred.另一个可能的返回值是ERROR_OPTION,这意味着发生了意外错误。
Selecting Files and Directories选择文件和目录
Method方法 Purpose目的
void setSelectedFile(File)
File getSelectedFile()
Sets or obtains the currently selected file or (if directory selection has been enabled) directory.设置或获取当前选定的文件或(如果已启用目录选择)目录。
void setSelectedFiles(File[])
File[] getSelectedFiles()
Sets or obtains the currently selected files if the file chooser is set to allow multiple selection.如果文件选择器设置为允许多选,则设置或获取当前选定的文件。
void setFileSelectionMode(int)
void getFileSelectionMode()
boolean isDirectorySelectionEnabled()
boolean isFileSelectionEnabled()
Sets or obtains the file selection mode. 设置或获取文件选择模式。Acceptable values are FILES_ONLY (the default), DIRECTORIES_ONLY, and FILES_AND_DIRECTORIES.可接受的值是FILES_ONLY(默认值)、DIRECTORIES_ONLYFILES_AND_DIRECTORIES
Interprets whether directories or files are selectable according to the current selection mode.解释根据当前选择模式是否可以选择目录或文件。
void setMultiSelectionEnabled(boolean)
boolean isMultiSelectionEnabled()
Sets or interprets whether multiple files can be selected at once. 设置或解释是否可以同时选择多个文件。By default, a user can choose only one file.默认情况下,用户只能选择一个文件。
void setAcceptAllFileFilterUsed(boolean)
boolean isAcceptAllFileFilterUsed()
Sets or obtains whether the AcceptAll file filter is used as an allowable choice in the choosable filter list; the default value is true.设置或获取AcceptAll文件筛选器是否用作可选择筛选器列表中的允许选项;默认值为true
Dialog createDialog(Component) Given a parent component, creates and returns a new dialog that contains this file chooser, is dependent on the parent's frame, and is centered over the parent.给定父组件,创建并返回包含此文件选择器的新对话框,该对话框依赖于父组件的框架,并位于父组件的中心。
Navigating the File Chooser's List浏览文件选择器列表
Method方法 Purpose目的
void ensureFileIsVisible(File) Scrolls the file chooser's list such that the indicated file is visible.滚动文件选择器的列表,以使指定的文件可见。
void setCurrentDirectory(File)
File getCurrentDirectory()
Sets or obtains the directory whose files are displayed in the file chooser's list.设置或获取其文件显示在文件选择器列表中的目录。
void changeToParentDirectory() Changes the list to display the current directory's parent.更改列表以显示当前目录的父目录。
void rescanCurrentDirectory() Checks the file system and updates the chooser's list.检查文件系统并更新选择器列表。
void setDragEnabled(boolean)
boolean getDragEnabled()
Sets or obtains the property that determines whether automatic drag handling is enabled. 设置或获取确定是否启用自动拖动处理的属性。See Drag and Drop and Data Transfer for more details.有关详细信息,请参阅拖放和数据传输
Customizing the File Chooser自定义文件选择器
Method方法 Purpose目的
void setAccessory(javax.swing.JComponent)
JComponent getAccessory()
Sets or obtains the file chooser's accessory component.设置或获取文件选择器的附件组件。
void setFileFilter(FileFilter)
FileFilter getFileFilter()
Sets or obtains the file chooser's primary file filter.设置或获取文件选择器的主文件筛选器。
void setFileView(FileView)
FileView getFileView()
Sets or obtains the chooser's file view.设置或获取选择器的文件视图。
FileFilter[] getChoosableFileFilters()
void addChoosableFileFilter(FileFilter)
boolean removeChoosableFileFilter(FileFilter)
void resetChoosableFileFilters()
FileFilter getAcceptAllFileFilter()
Sets, obtains, or modifies the list of user-choosable file filters.设置、获取或修改用户可选择的文件筛选器列表。
void setFileHidingEnabled(boolean)
boolean isFileHidingEnabled()
Sets or obtains whether hidden files are displayed.设置或获取是否显示隐藏文件。
void setControlButtonsAreShown(boolean)
boolean getControlButtonsAreShown()
Sets or obtains the property that indicates whether the Approve and Cancel buttons are shown in the file chooser. 设置或获取属性,该属性指示“文件选择器”中是否显示“批准”和“取消”按钮。This property is true by default.默认情况下,此属性为true

Examples That Use File Choosers使用文件选择器的示例

This table shows the examples that use file choosers and points to where those examples are described.下表显示了使用文件选择器的示例,并指出了这些示例的描述位置。

Example示例 Where Described描述位置 Notes备注
FileChooserDemo This section本节 Displays an open dialog and a save dialog.显示打开对话框和保存对话框。
FileChooserDemo2 This section本节 Uses a file chooser with custom filtering, a custom file view, and an accessory component.使用具有自定义筛选、自定义文件视图和附件组件的文件选择器。
JWSFileChooserDemo This section本节 Uses the JNLP API to open and save files.使用JNLP API打开和保存文件。

Previous page: How to Use Editor Panes and Text Panes
Next page: How to Use Formatted Text Fields