⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 filechooser.html

📁 jsf、swing的官方指南
💻 HTML
📖 第 1 页 / 共 4 页
字号:
<div class="linkBHEAD"><a href="toolbar.html">How to Use Tool Bars</a></div><div class="linkBHEAD"><a href="tooltip.html">How to Use Tool Tips</a></div><div class="linkBHEAD"><a href="tree.html">How to Use Trees</a></div><div class="linkAHEAD"><a href="icon.html">How to Use Icons</a></div><div class="linkAHEAD"><a href="border.html">How to Use Borders</a></div><div class="linkAHEAD"><a href="problems.html">Solving Common Component Problems</a></div></div>    </div>    <div id=MainFlow class=MainFlow_indented>            <span id=BreadCrumbs>                <a href=../../index.html target=_top>Home Page</a>                &gt;                <a href=../index.html target=_top>Creating a GUI with JFC/Swing</a>                &gt;                <a href=index.html target=_top>Using Swing Components</a>            </span>            <div class=NavBit>                <a target=_top href=editorpane.html>&laquo;&nbsp;Previous</a>&nbsp;&bull;&nbsp;<a target=_top href=../TOC.html>Trail</a>&nbsp;&bull;&nbsp;<a target=_top href=formattedtextfield.html>Next&nbsp;&raquo;</a>            </div>            <div id=PageTitle>How to Use File Choosers</div>            <blockquote>File choosers provide a GUI for navigating the file system,and then either choosing a file or directory from a listor entering the name of a file or directory.To display a file chooser, you usually use the <code>JFileChooser</code> APIto show a modal<a href="dialog.html">dialog</a>containing the file chooser.Another way to present a file chooser is to add an instance of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/javax/swing/JFileChooser.html"><code>JFileChooser</code></a> to a container.<p><blockquote><hr><strong>Note:</strong>&nbsp; If you intend to distribute your program as an unsignedJava<font size="-2"><sup>TM</sup></font> Web Start application,then instead of using the <code>JFileChooser</code> APIyou should use the file services providedby the JNLP API.These services &#151;<code>FileOpenService</code> and <code>FileSaveService</code> &#151;not only provide support for choosing files in a restricted environment,but also take care of actually opening and saving them.An example of using these services is in<a href="examples/index.html#JWSFileChooserDemo">JWSFileChooserDemo</a>.Documentation for using the JNLP API is in the<a class="TutorialLink" target="_top" href="../../deployment/webstart/index.html">Java Web Start</a> lesson.<hr></blockquote><p>The rest of this section discusses how to use the <code>JFileChooser</code> API.A <code>JFileChooser</code> objectonly presents the GUI for choosing files.Your program is responsible for doing somethingwith the chosen file,such as opening or saving it.Refer to<a class="TutorialLink" target="_top" href="../../essential/io/index.html">Basic I/O</a> for information on how to read and write files.<p>The <code>JFileChooser</code> API makes it easy to bring up open and save dialogs.The look and feel determines whatthese standard dialogs look like and how they differ.In the Java look and feel,the save dialog looks the sameas the open dialog,except for the title on the dialog's windowand the text on the button that approves the operation.Here is a picture of the Java look and feel's standard open dialog:<p><center><IMG SRC="../../figures/uiswing/components/FileChooserOpenMetal.png" WIDTH="508" HEIGHT="360" ALIGN="BOTTOM" ALT="A standard open dialog shown in the Java look and feel"></center></p><p>Here's a snapshot of an application that brings up an open dialog and a save dialog.<p><p><center><IMG SRC="../../figures/uiswing/components/FileChooserDemo2Metal.png" WIDTH="272" HEIGHT="163" ALIGN="BOTTOM" ALT="A program that brings up an open or save dialog"></center></p><p><blockquote><hr><strong>Try this:</strong>&nbsp;<ol><li> Compile and run      FileChooserDemo.See the <a href="examples/index.html#FileChooserDemo" target="_top">examples index</a> for links to all the files required by this example.<li> Click the <strong>Open a File...</strong> button.     Navigate around the file chooser, choose a file,     and click the dialog's <strong>Open</strong> button.<li> Use the <strong>Save a File...</strong> button     to bring up a save dialog.     Try to use all of the controls on the file chooser.<li> In the source file <a class="SourceLink" target="_blank" href="examples/FileChooserDemo.java"><code>FileChooserDemo.java</code></a>,    change the file selection mode to directories-only mode.     (Search for <code>DIRECTORIES_ONLY</code> and     uncomment the line that contains it.)     Then compile and run the example again.     You'll only be able to see and select directories,     not ordinary files.</ol><hr></blockquote>Bringing up a standard open dialogrequires only two lines of code:<blockquote><pre>//Create a file chooserfinal JFileChooser fc = new JFileChooser();...<em>//In response to a button click:</em>int returnVal = fc.showOpenDialog(<em>aComponent</em>);</pre></blockquote>The argument to the <code>showOpenDialog</code> methodspecifies the parent component for the dialog.The parent component affects the position of the dialogand the frame that the dialog depends on.For example, the Java look and feel places the dialog directly over the parent component.If the parent component is in a frame,then the dialog is dependent on that frame,disappearing when the frame is iconifiedand reappearing when the frame is deiconified.<p>By default,a file chooser that hasn't been shown beforedisplays all files in the user's home directory.You can specify the file chooser's initial directoryusing one of <code>JFileChooser</code>'s other constructors,or you can set the directorywith the <code>setCurrentDirectory</code> method.<p>The call to <code>showOpenDialog</code> appears in the<code>actionPerformed</code> method of the <strong>Open a File...</strong>button's action listener:<blockquote><pre>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);        }   } ...}</pre></blockquote>The <code>show<em>Xxx</em>Dialog</code>methods return an integerthat indicates whether the user selected a file.Depending on how you use a file chooser, it's often sufficient to check whether the return value is<code>APPROVE_OPTION</code> and to do nothing for any other value.To get the chosen file(or directory, if you set up the file chooserto allow directory selections),call <code>getSelectedFile</code>on the file chooser.This method returns an instance of<a class="APILink" target="_blank" href="http://java.sun.com/javase/6/docs/api/java/io/File.html"><code>File</code></a>.<p>The example gets the name of the file anduses it in the log message.You can call other methods on the <code>File</code> object,such as <code>getPath</code>,<code>isDirectory</code>, or <code>exists</code>to get information about the file.You can also call other methods such as<code>delete</code> and <code>rename</code>to change the file in some way.Of course, you might also want to open or save thefile using one of the reader or writer classesprovided by the Java platform.See<a class="TutorialLink" target="_top" href="../../essential/io/index.html">Basic I/O</a> for information about using readers and writers toread and write data to the file system.<p>The example program uses the sameinstance of <code>JFileChooser</code>to display a standard save dialog.This time the program calls <code>showSaveDialog</code>:<blockquote><pre>int returnVal = fc.showSaveDialog(FileChooserDemo.this);</pre></blockquote>By using the same file chooser instance to displayits open and save dialogs, the program reaps these benefits:<ul><li> The chooser remembers the current directory between     uses so the open and save versions automatically share the     same current directory.<li> You have to customize only one file chooser,     and the customizations apply to both the open     and save versions of it.</ul>Finally, the example program has commented-out lines of codethat let you change the file selection mode.For example, the following line of code makes the file chooserable to select only directories, and not files:<blockquote><pre>fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);</pre></blockquote>Another possible selection mode is <code>FILES_AND_DIRECTORIES</code>.The default is <code>FILES_ONLY</code>.The following picture shows an open dialog with the file selection mode set to <code>DIRECTORIES_ONLY</code>.Note that, in the Java look and feel at least, only directories are visible &#151; not files.<p><center><IMG SRC="../../figures/uiswing/components/FileChooserDirectoriesMetal.png" WIDTH="508" HEIGHT="360" ALIGN="BOTTOM" ALT="A file chooser in DIRECTORIES_ONLY mode"></center></p><p>If you want to create a file chooserfor a task other than opening or saving,or if you want to customize the file chooser,keep reading.We'll discuss the following topics:<ul><li> <a href="#advancedexample">Another Example: FileChooserDemo2</a><li> <a href="#customtask">Using a File Chooser for a Custom Task</a><li> <a href="#filters">Filtering the List of Files</a><li> <a href="#fileview">Customizing the File View</a><li> <a href="#accessory">Providing an Accessory Component</a><li> <a href="#api">The File Chooser API</a><li> <a href="#eg">Examples that Use File Choosers</a></ul><a name="advancedexample"></blockquote><h3>Another Example: FileChooserDemo2</h3></a><blockquote>Let's look at<a href="examples/index.html#FileChooserDemo2"><code>FileChooserDemo2</code></a>,a modified version of the previous demo program thatuses more of the <code>JFileChooser</code> API.This example uses a file chooser that has beencustomized in several ways.Like the original example, the user invokesa file chooser with the push of a button.Here's a picture of the file chooser: <p><center><IMG SRC="../../figures/uiswing/components/FileChooserDemo3Metal.png" WIDTH="536" HEIGHT="360" ALIGN="BOTTOM" ALT="A file chooser with various customizations"></center></p><p><p>As the figure shows, this file chooserhas 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 componentthat displays a thumbnail sketch of the currently selectedimage file.<p>The remainder of this section shows you the codethat creates and customizes this file chooser.See the <a href="examples/index.html#FileChooserDemo2" target="_top">examples index</a> for links to all the files required by this example.</blockquote><a name="customtask"><h3>Using a File Chooser for a Custom Task</h3></a><blockquote>As you've seen, <code>JFileChooser</code>provides <code>showOpenDialog</code> for displaying an open dialogand <code>showSaveDialog</code> for displaying a save dialog.<p>The class has another method, <code>showDialog</code>,for displaying a file chooser for a custom task in a dialog.In the Java look and feel, the only difference between this dialogand the other file chooser dialogs is the title on the dialog windowand the label on the approve button.Here's the code from <code>FileChooserDemo2</code>that brings up the file chooser dialog for the<strong>Attach</strong> task:<blockquote><pre>JFileChooser fc = new JFileChooser();int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach");</pre></blockquote>The first argument to the <code>showDialog</code> methodis the parent component for the dialog.The second argument is a <code>String</code> thatprovides both the title for the dialog windowand the label for the approve button.<p>Once again, the file chooser doesn't do anything withthe selected file.The program is responsible for implementing the custom taskfor which the file chooser was created.</blockquote><a name="filters"><h3>Filtering the List of Files</h3></a><blockquote>By default, a file chooser displays all of the filesand directories that it detects, except hidden files.A program can apply one or more <em>file filters</em>to a file chooser so that the chooser shows only some files.The file chooser calls the filter's <code>accept</code> methodfor each file to determine whether it should be displayed.A file filter accepts or rejects a file basedon some 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's not displayed.

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -