1981 lines · 66.3 KB · Java
RawDownload
/* * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation.  Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javax.swing; import javax.swing.event.*;import javax.swing.filechooser.*;import javax.swing.plaf.FileChooserUI; import javax.accessibility.*; import java.io.File;import java.io.ObjectOutputStream;import java.io.IOException; import java.util.Vector;import java.awt.AWTEvent;import java.awt.Component;import java.awt.Container;import java.awt.BorderLayout;import java.awt.Window;import java.awt.Dialog;import java.awt.Frame;import java.awt.GraphicsEnvironment;import java.awt.HeadlessException;import java.awt.EventQueue;import java.awt.Toolkit;import java.awt.event.*;import java.beans.PropertyChangeListener;import java.beans.PropertyChangeEvent;import java.lang.ref.WeakReference; /** * <code>JFileChooser</code> provides a simple mechanism for the user to * choose a file. * For information about using <code>JFileChooser</code>, see * <a href="http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html">How to Use File Choosers</a>, * a section in <em>The Java Tutorial</em>. * * <p> * * The following code pops up a file chooser for the user's home directory that * sees only .jpg and .gif images: * <pre> *    JFileChooser chooser = new JFileChooser(); *    FileNameExtensionFilter filter = new FileNameExtensionFilter( *        "JPG & GIF Images", "jpg", "gif"); *    chooser.setFileFilter(filter); *    int returnVal = chooser.showOpenDialog(parent); *    if(returnVal == JFileChooser.APPROVE_OPTION) { *       System.out.println("You chose to open this file: " + *            chooser.getSelectedFile().getName()); *    } * </pre> * <p> * <strong>Warning:</strong> Swing is not thread safe. For more * information see <a * href="package-summary.html#threading">Swing's Threading * Policy</a>. * * @beaninfo *   attribute: isContainer false * description: A component which allows for the interactive selection of a file. * * @author Jeff Dinkins * */public class JFileChooser extends JComponent implements Accessible {     /**     * @see #getUIClassID     * @see #readObject     */    private static final String uiClassID = "FileChooserUI";     // ************************    // ***** Dialog Types *****    // ************************     /**     * Type value indicating that the <code>JFileChooser</code> supports an     * "Open" file operation.     */    public static final int OPEN_DIALOG = 0;     /**     * Type value indicating that the <code>JFileChooser</code> supports a     * "Save" file operation.     */    public static final int SAVE_DIALOG = 1;     /**     * Type value indicating that the <code>JFileChooser</code> supports a     * developer-specified file operation.     */    public static final int CUSTOM_DIALOG = 2;      // ********************************    // ***** Dialog Return Values *****    // ********************************     /**     * Return value if cancel is chosen.     */    public static final int CANCEL_OPTION = 1;     /**     * Return value if approve (yes, ok) is chosen.     */    public static final int APPROVE_OPTION = 0;     /**     * Return value if an error occured.     */    public static final int ERROR_OPTION = -1;      // **********************************    // ***** JFileChooser properties *****    // **********************************      /** Instruction to display only files. */    public static final int FILES_ONLY = 0;     /** Instruction to display only directories. */    public static final int DIRECTORIES_ONLY = 1;     /** Instruction to display both files and directories. */    public static final int FILES_AND_DIRECTORIES = 2;     /** Instruction to cancel the current selection. */    public static final String CANCEL_SELECTION = "CancelSelection";     /**     * Instruction to approve the current selection     * (same as pressing yes or ok).     */    public static final String APPROVE_SELECTION = "ApproveSelection";     /** Identifies change in the text on the approve (yes, ok) button. */    public static final String APPROVE_BUTTON_TEXT_CHANGED_PROPERTY = "ApproveButtonTextChangedProperty";     /**     * Identifies change in the tooltip text for the approve (yes, ok)     * button.     */    public static final String APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY = "ApproveButtonToolTipTextChangedProperty";     /** Identifies change in the mnemonic for the approve (yes, ok) button. */    public static final String APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY = "ApproveButtonMnemonicChangedProperty";     /** Instruction to display the control buttons. */    public static final String CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY = "ControlButtonsAreShownChangedProperty";     /** Identifies user's directory change. */    public static final String DIRECTORY_CHANGED_PROPERTY = "directoryChanged";     /** Identifies change in user's single-file selection. */    public static final String SELECTED_FILE_CHANGED_PROPERTY = "SelectedFileChangedProperty";     /** Identifies change in user's multiple-file selection. */    public static final String SELECTED_FILES_CHANGED_PROPERTY = "SelectedFilesChangedProperty";     /** Enables multiple-file selections. */    public static final String MULTI_SELECTION_ENABLED_CHANGED_PROPERTY = "MultiSelectionEnabledChangedProperty";     /**     * Says that a different object is being used to find available drives     * on the system.     */    public static final String FILE_SYSTEM_VIEW_CHANGED_PROPERTY = "FileSystemViewChanged";     /**     * Says that a different object is being used to retrieve file     * information.     */    public static final String FILE_VIEW_CHANGED_PROPERTY = "fileViewChanged";     /** Identifies a change in the display-hidden-files property. */    public static final String FILE_HIDING_CHANGED_PROPERTY = "FileHidingChanged";     /** User changed the kind of files to display. */    public static final String FILE_FILTER_CHANGED_PROPERTY = "fileFilterChanged";     /**     * Identifies a change in the kind of selection (single,     * multiple, etc.).     */    public static final String FILE_SELECTION_MODE_CHANGED_PROPERTY = "fileSelectionChanged";     /**     * Says that a different accessory component is in use     * (for example, to preview files).     */    public static final String ACCESSORY_CHANGED_PROPERTY = "AccessoryChangedProperty";     /**     * Identifies whether a the AcceptAllFileFilter is used or not.     */    public static final String ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY = "acceptAllFileFilterUsedChanged";     /** Identifies a change in the dialog title. */    public static final String DIALOG_TITLE_CHANGED_PROPERTY = "DialogTitleChangedProperty";     /**     * Identifies a change in the type of files displayed (files only,     * directories only, or both files and directories).     */    public static final String DIALOG_TYPE_CHANGED_PROPERTY = "DialogTypeChangedProperty";     /**     * Identifies a change in the list of predefined file filters     * the user can choose from.     */    public static final String CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY = "ChoosableFileFilterChangedProperty";     // ******************************    // ***** instance variables *****    // ******************************     private String dialogTitle = null;    private String approveButtonText = null;    private String approveButtonToolTipText = null;    private int approveButtonMnemonic = 0;     private Vector<FileFilter> filters = new Vector<FileFilter>(5);    private JDialog dialog = null;    private int dialogType = OPEN_DIALOG;    private int returnValue = ERROR_OPTION;    private JComponent accessory = null;     private FileView fileView = null;     private boolean controlsShown = true;     private boolean useFileHiding = true;    private static final String SHOW_HIDDEN_PROP = "awt.file.showHiddenFiles";     // Listens to changes in the native setting for showing hidden files.    // The Listener is removed and the native setting is ignored if    // setFileHidingEnabled() is ever called.    private transient PropertyChangeListener showFilesListener = null;     private int fileSelectionMode = FILES_ONLY;     private boolean multiSelectionEnabled = false;     private boolean useAcceptAllFileFilter = true;     private boolean dragEnabled = false;     private FileFilter fileFilter = null;     private FileSystemView fileSystemView = null;     private File currentDirectory = null;    private File selectedFile = null;    private File[] selectedFiles;     // *************************************    // ***** JFileChooser Constructors *****    // *************************************     /**     * Constructs a <code>JFileChooser</code> pointing to the user's     * default directory. This default depends on the operating system.     * It is typically the "My Documents" folder on Windows, and the     * user's home directory on Unix.     */    public JFileChooser() {        this((File) null, (FileSystemView) null);    }     /**     * Constructs a <code>JFileChooser</code> using the given path.     * Passing in a <code>null</code>     * string causes the file chooser to point to the user's default directory.     * This default depends on the operating system. It is     * typically the "My Documents" folder on Windows, and the user's     * home directory on Unix.     *     * @param currentDirectoryPath  a <code>String</code> giving the path     *                          to a file or directory     */    public JFileChooser(String currentDirectoryPath) {        this(currentDirectoryPath, (FileSystemView) null);    }     /**     * Constructs a <code>JFileChooser</code> using the given <code>File</code>     * as the path. Passing in a <code>null</code> file     * causes the file chooser to point to the user's default directory.     * This default depends on the operating system. It is     * typically the "My Documents" folder on Windows, and the user's     * home directory on Unix.     *     * @param currentDirectory  a <code>File</code> object specifying     *                          the path to a file or directory     */    public JFileChooser(File currentDirectory) {        this(currentDirectory, (FileSystemView) null);    }     /**     * Constructs a <code>JFileChooser</code> using the given     * <code>FileSystemView</code>.     */    public JFileChooser(FileSystemView fsv) {        this((File) null, fsv);    }      /**     * Constructs a <code>JFileChooser</code> using the given current directory     * and <code>FileSystemView</code>.     */    public JFileChooser(File currentDirectory, FileSystemView fsv) {        setup(fsv);        setCurrentDirectory(currentDirectory);    }     /**     * Constructs a <code>JFileChooser</code> using the given current directory     * path and <code>FileSystemView</code>.     */    public JFileChooser(String currentDirectoryPath, FileSystemView fsv) {        setup(fsv);        if(currentDirectoryPath == null) {            setCurrentDirectory(null);        } else {            setCurrentDirectory(fileSystemView.createFileObject(currentDirectoryPath));        }    }     /**     * Performs common constructor initialization and setup.     */    protected void setup(FileSystemView view) {        installShowFilesListener();         if(view == null) {            view = FileSystemView.getFileSystemView();        }        setFileSystemView(view);        updateUI();        if(isAcceptAllFileFilterUsed()) {            setFileFilter(getAcceptAllFileFilter());        }        enableEvents(AWTEvent.MOUSE_EVENT_MASK);    }     private void installShowFilesListener() {        // Track native setting for showing hidden files        Toolkit tk = Toolkit.getDefaultToolkit();        Object showHiddenProperty = tk.getDesktopProperty(SHOW_HIDDEN_PROP);        if (showHiddenProperty instanceof Boolean) {            useFileHiding = !((Boolean)showHiddenProperty).booleanValue();            showFilesListener = new WeakPCL(this);            tk.addPropertyChangeListener(SHOW_HIDDEN_PROP, showFilesListener);        }    }     /**     * Sets the <code>dragEnabled</code> property,     * which must be <code>true</code> to enable     * automatic drag handling (the first part of drag and drop)     * on this component.     * The <code>transferHandler</code> property needs to be set     * to a non-<code>null</code> value for the drag to do     * anything.  The default value of the <code>dragEnabled</code>     * property     * is <code>false</code>.     *     * <p>     *     * When automatic drag handling is enabled,     * most look and feels begin a drag-and-drop operation     * whenever the user presses the mouse button over an item     * and then moves the mouse a few pixels.     * Setting this property to <code>true</code>     * can therefore have a subtle effect on     * how selections behave.     *     * <p>     *     * Some look and feels might not support automatic drag and drop;     * they will ignore this property.  You can work around such     * look and feels by modifying the component     * to directly call the <code>exportAsDrag</code> method of a     * <code>TransferHandler</code>.     *     * @param b the value to set the <code>dragEnabled</code> property to     * @exception HeadlessException if     *            <code>b</code> is <code>true</code> and     *            <code>GraphicsEnvironment.isHeadless()</code>     *            returns <code>true</code>     * @see java.awt.GraphicsEnvironment#isHeadless     * @see #getDragEnabled     * @see #setTransferHandler     * @see TransferHandler     * @since 1.4     *     * @beaninfo     *  description: determines whether automatic drag handling is enabled     *        bound: false     */    public void setDragEnabled(boolean b) {        if (b && GraphicsEnvironment.isHeadless()) {            throw new HeadlessException();        }        dragEnabled = b;    }     /**     * Gets the value of the <code>dragEnabled</code> property.     *     * @return  the value of the <code>dragEnabled</code> property     * @see #setDragEnabled     * @since 1.4     */    public boolean getDragEnabled() {        return dragEnabled;    }     // *****************************    // ****** File Operations ******    // *****************************     /**     * Returns the selected file. This can be set either by the     * programmer via <code>setSelectedFile</code> or by a user action, such as     * either typing the filename into the UI or selecting the     * file from a list in the UI.     *     * @see #setSelectedFile     * @return the selected file     */    public File getSelectedFile() {        return selectedFile;    }     /**     * Sets the selected file. If the file's parent directory is     * not the current directory, changes the current directory     * to be the file's parent directory.     *     * @beaninfo     *   preferred: true     *       bound: true     *     * @see #getSelectedFile     *     * @param file the selected file     */    public void setSelectedFile(File file) {        File oldValue = selectedFile;        selectedFile = file;        if(selectedFile != null) {            if (file.isAbsolute() && !getFileSystemView().isParent(getCurrentDirectory(), selectedFile)) {                setCurrentDirectory(selectedFile.getParentFile());            }            if (!isMultiSelectionEnabled() || selectedFiles == null || selectedFiles.length == 1) {                ensureFileIsVisible(selectedFile);            }        }        firePropertyChange(SELECTED_FILE_CHANGED_PROPERTY, oldValue, selectedFile);    }     /**     * Returns a list of selected files if the file chooser is     * set to allow multiple selection.     */    public File[] getSelectedFiles() {        if(selectedFiles == null) {            return new File[0];

Lines 1–500 of 1981.