The Java Tutorials have been written for JDK 8.Java教程是为JDK 8编写的。Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available.本页中描述的示例和实践没有利用后续版本中引入的改进,并且可能使用不再可用的技术。See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases.有关Java SE 9及其后续版本中更新的语言特性的摘要,请参阅Java语言更改。
See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.有关所有JDK版本的新功能、增强功能以及已删除或不推荐的选项的信息,请参阅JDK发行说明。
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
的实例添加到容器中。
If you intend to distribute your program as a sandbox Java Web Start application, then instead of using the 如果您打算将程序作为沙盒Java Web Start应用程序分发,那么您应该使用JNLP API提供的文件服务,而不是使用JFileChooser
API you should use the file services provided by the 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. FileOpenService
和FileSaveService
不仅支持在受限环境中选择文件,而且还负责实际打开和保存文件。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.或者,要自己编译和运行示例,请参考示例索引。
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外观中标准打开对话框的图片:
Here is a picture of an application called 下面是一个名为FileChooserDemo
that brings up an open dialog and a save dialog.FileChooserDemo
的应用程序的图片,该应用程序将打开一个打开对话框和一个保存对话框。
FileChooserDemo.java
, change the file selection mode to directories-only mode. FileChooserDemo.java
中,将文件选择模式更改为仅目录模式。DIRECTORIES_ONLY
and uncomment the line that contains it.) DIRECTORIES_ONLY
并取消对包含它的行的注释。)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
对象上的其他方法,如getPath
、isDirectory
或exists
,以获取有关文件的信息。You can also call other methods such as 您还可以调用其他方法,如delete
and rename
to change the file in some way. delete
和rename
,以某种方式更改文件。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_DIRECTORIES
。The default is 默认值为FILES_ONLY
. FILES_ONLY
。The following picture shows an open dialog with the file selection mode set to 下图显示了一个打开的对话框,其中文件选择模式设置为DIRECTORIES_ONLY
. DIRECTORIES_ONLY
。Note that, in the Java look and feel at least, only directories are visible not files.请注意,至少在Java外观中,只有目录是可见的;不是文件。
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:我们将讨论以下主题:
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:与原始示例一样,用户只需按下按钮即可调用文件选择器。以下是文件选择器的图片:
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.有关此示例所需的所有文件的链接,请参阅示例索引。
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.该程序负责实现为其创建文件选择器的自定义任务。
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方法,以确定是否应显示该文件。accept
method for each file to determine whether it should be displayed. 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.例如,应用程序控制的筛选器仅查看内置筛选接受的文件。
setFileHidingEnabled(false)
to show hidden files.setFileHidingEnabled(false)
以显示隐藏文件。FileFilter
, instantiate it, and use the instance as an argument to the setFileFilter
method. FileFilter
的自定义子类,实例化它,并将该实例用作setFileFilter
方法的参数。FileChooserDemo2
fc.addChoosableFileFilter(new ImageFilter());
fc.setAcceptAllFileFilterUsed(false);
ImageFilter.java
and is a subclass of FileFilter
. ImageFilter.java
中实现,是FileFilter
的一个子类。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; }
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; } }
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)
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)
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)
null
to indicate that the look and feel should figure it out. null
,以表明外观应该能够解决这个问题。f.getName()
.f.getName()
。String getDescription(File f)
null
to indicate that the look and feel should figure it out.null
,以指示外观应该能够解决此问题。Boolean isTraversable(File f)
null
to indicate that the look and feel should figure it out. null
,以表明外观应该能够解决这个问题。isTraversable
method should never return true
for a non-directory.isTraversable
方法不应返回true
。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.loadImage
和repaint
方法使用File
对象加载图像并重新绘制附件组件。
The API for using file choosers falls into these categories:使用文件选择器的API分为以下几类:
JFileChooser() JFileChooser(File) JFileChooser(String)
|
File and String arguments, when present, provide the initial directory.File 和String 参数(如果存在)提供初始目录。 |
int showOpenDialog(Component) int showSaveDialog(Component) int showDialog(Component, String) |
APPROVE_OPTION if the user approved the operation and CANCEL_OPTION if the user cancelled it. APPROVE_OPTION ,如果用户取消操作,则返回CANCEL_OPTION 。ERROR_OPTION , which means an unanticipated error occurred.ERROR_OPTION ,这意味着发生了意外错误。 |
void setSelectedFile(File) File getSelectedFile() |
|
void setSelectedFiles(File[]) File[] getSelectedFiles() |
|
void setFileSelectionMode(int) void getFileSelectionMode() boolean isDirectorySelectionEnabled() boolean isFileSelectionEnabled() |
FILES_ONLY (the default), DIRECTORIES_ONLY , and FILES_AND_DIRECTORIES .FILES_ONLY (默认值)、DIRECTORIES_ONLY 和FILES_AND_DIRECTORIES 。 |
void setMultiSelectionEnabled(boolean) boolean isMultiSelectionEnabled() |
|
void setAcceptAllFileFilterUsed(boolean) boolean isAcceptAllFileFilterUsed() |
AcceptAll file filter is used as an allowable choice in the choosable filter list; the default value is true .AcceptAll 文件筛选器是否用作可选择筛选器列表中的允许选项;默认值为true 。 |
Dialog createDialog(Component) |
void ensureFileIsVisible(File) |
|
void setCurrentDirectory(File) File getCurrentDirectory() |
|
void changeToParentDirectory() |
|
void rescanCurrentDirectory() |
|
void setDragEnabled(boolean) boolean getDragEnabled() |
void setAccessory(javax.swing.JComponent) JComponent getAccessory() |
|
void setFileFilter(FileFilter) FileFilter getFileFilter() |
|
void setFileView(FileView) FileView getFileView() |
|
FileFilter[] getChoosableFileFilters() void addChoosableFileFilter(FileFilter) boolean removeChoosableFileFilter(FileFilter) void resetChoosableFileFilters() FileFilter getAcceptAllFileFilter() |
|
void setFileHidingEnabled(boolean) boolean isFileHidingEnabled() |
|
void setControlButtonsAreShown(boolean) boolean getControlButtonsAreShown() |
true 。 |
This table shows the examples that use file choosers and points to where those examples are described.下表显示了使用文件选择器的示例,并指出了这些示例的描述位置。
FileChooserDemo |
||
FileChooserDemo2 |
||
JWSFileChooserDemo |