Java Tutorial/Swing/JFileChooser
Содержание
- 1 A convenience implementation of FileFilter that filters out all files except for those type extensions that it knows about.
- 2 ActionListener for JFileChooser in Your JFrame
- 3 Adding Accessory Panels
- 4 Adding a Filter to a File Chooser Dialog
- 5 Adding an ActionListener to a JFileChooser to listen for selection of the approval or cancel actions.
- 6 Changing the Text of the Approve Button in a JFileChooser Dialog
- 7 Creating a JFileChooser Dialog
- 8 Custom FileView for Some Java-Related File Types
- 9 Customizing a JFileChooser Look and Feel
- 10 Determining If a File Is Hidden
- 11 Determining If the Approve or Cancel Button Was Clicked in a JFileChooser Dialog
- 12 Disable the JFileChooser "New folder" button
- 13 Displaying Only Directories in a File Chooser Dialog
- 14 Enabling Multiple Selections in a JFileChooser Dialog
- 15 Get Directory Choice
- 16 Get File Choice
- 17 Getting and Setting the Current Directory of a JFileChooser Dialog
- 18 Getting and Setting the Selected File of a JFileChooser Dialog
- 19 Getting the File-Type Icon of a File
- 20 Getting the Large File-Type Icon of a File
- 21 JFileChooser
- 22 JFileChooser is a standard dialog for selecting a file from the file system.
- 23 JFileChooser Selection Option: JFileChooser.APPROVE_OPTION, JFileChooser.CANCEL_OPTION
- 24 Listening for Approve and Cancel Events in a JFileChooser Dialog
- 25 Listening for Changes to the Selected File in a JFileChooser Dialog
- 26 Localize a JFileChooser
- 27 Select a directory with a JFileChooser
- 28 Showing Hidden Files in a JFileChooser Dialog
- 29 The JFileChooser supports three selection modes: files only, directories only, and files and directories
- 30 To enable the display of hidden files
- 31 Using a JFileChooser in Your JFrame
- 32 Using JFileChooser
- 33 Working with File Filters
A convenience implementation of FileFilter that filters out all files except for those type extensions that it knows about.
/*
* Copyright (c) 2002 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* -Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduct the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT
* BE LIABLE FOR ANY DAMAGES OR LIABILITIES SUFFERED BY LICENSEE AS A RESULT
* OF OR RELATING TO USE, MODIFICATION OR DISTRIBUTION OF THE SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN
* IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that Software is not designed, licensed or intended for
* use in the design, construction, operation or maintenance of any nuclear
* facility.
*/
/*
* @(#)EasyFileFilter.java 1.13 02/06/13
*/
import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.filechooser.FileFilter;
/**
* A convenience implementation of FileFilter that filters out all files except
* for those type extensions that it knows about.
*
* Extensions are of the type ".foo", which is typically found on Windows and
* Unix boxes, but not on Macinthosh. Case is ignored.
*
* Example - create a new filter that filerts out all files but gif and jpg
* image files:
*
* JFileChooser chooser = new JFileChooser(); EasyFileFilter filter = new
* EasyFileFilter( new String{"gif", "jpg"}, "JPEG & GIF Images")
* chooser.addChoosableFileFilter(filter); chooser.showOpenDialog(this);
*
* @version 1.13 06/13/02
* @author Jeff Dinkins
*/
public class EasyFileFilter extends FileFilter {
private Hashtable<String, FileFilter> filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
/**
* Creates a file filter. If no filters are added, then all files are
* accepted.
*
* @see #addExtension
*/
public EasyFileFilter() {
this.filters = new Hashtable<String, FileFilter>();
}
/**
* Creates a file filter that accepts files with the given extension.
* Example: new EasyFileFilter("jpg");
*
* @see #addExtension
*/
public EasyFileFilter(String extension) {
this(extension, null);
}
/**
* Creates a file filter that accepts the given file type. Example: new
* EasyFileFilter("jpg", "JPEG Image Images");
*
* Note that the "." before the extension is not needed. If provided, it
* will be ignored.
*
* @see #addExtension
*/
public EasyFileFilter(String extension, String description) {
this();
if (extension != null)
addExtension(extension);
if (description != null)
setDescription(description);
}
/**
* Creates a file filter from the given string array. Example: new
* EasyFileFilter(String {"gif", "jpg"});
*
* Note that the "." before the extension is not needed adn will be ignored.
*
* @see #addExtension
*/
public EasyFileFilter(String[] filters) {
this(filters, null);
}
/**
* Creates a file filter from the given string array and description.
* Example: new EasyFileFilter(String {"gif", "jpg"}, "Gif and JPG Images");
*
* Note that the "." before the extension is not needed and will be ignored.
*
* @see #addExtension
*/
public EasyFileFilter(String[] filters, String description) {
this();
for (int i = 0; i < filters.length; i++) {
// add filters one by one
addExtension(filters[i]);
}
if (description != null)
setDescription(description);
}
/**
* Return true if this file should be shown in the directory pane, false if
* it shouldn"t.
*
* Files that begin with "." are ignored.
*
* @see #getExtension
* @see FileFilter#accept
*/
public boolean accept(File f) {
if (f != null) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null && filters.get(getExtension(f)) != null) {
return true;
}
}
return false;
}
/**
* Return the extension portion of the file"s name .
*
* @see #getExtension
* @see FileFilter#accept
*/
public String getExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf(".");
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase();
}
}
return null;
}
/**
* Adds a filetype "dot" extension to filter against.
*
* For example: the following code will create a filter that filters out all
* files except those that end in ".jpg" and ".tif":
*
* EasyFileFilter filter = new EasyFileFilter(); filter.addExtension("jpg");
* filter.addExtension("tif");
*
* Note that the "." before the extension is not needed and will be ignored.
*/
public void addExtension(String extension) {
if (filters == null) {
filters = new Hashtable<String, FileFilter>(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
/**
* Returns the human readable description of this filter. For example: "JPEG
* and GIF Image Files (*.jpg, *.gif)"
*
* @see FileFilter#getDescription
*/
public String getDescription() {
if (fullDescription == null) {
if (description == null || isExtensionListInDescription()) {
fullDescription = description == null ? "(" : description + " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if (extensions != null) {
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements()) {
fullDescription += ", ." + (String) extensions.nextElement();
}
}
fullDescription += ")";
} else {
fullDescription = description;
}
}
return fullDescription;
}
/**
* Sets the human readable description of this filter. For example:
* filter.setDescription("Gif and JPG Images");
*
*/
public void setDescription(String description) {
this.description = description;
fullDescription = null;
}
/**
* Determines whether the extension list (.jpg, .gif, etc) should show up in
* the human readable description.
*
* Only relevent if a description was provided in the constructor or using
* setDescription();
*
*/
public void setExtensionListInDescription(boolean b) {
useExtensionsInDescription = b;
fullDescription = null;
}
/**
* Returns whether the extension list (.jpg, .gif, etc) should show up in
* the human readable description.
*
* Only relevent if a description was provided in the constructor or using
* setDescription();
*
*/
public boolean isExtensionListInDescription() {
return useExtensionsInDescription;
}
}
ActionListener for JFileChooser in Your JFrame
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileSamplePanel {
public static void main(String args[]) {
JFrame frame = new JFrame("JFileChooser Popup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel directoryLabel = new JLabel(" ");
directoryLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(directoryLabel, BorderLayout.NORTH);
final JLabel filenameLabel = new JLabel(" ");
filenameLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(filenameLabel, BorderLayout.SOUTH);
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setControlButtonsAreShown(false);
frame.add(fileChooser, BorderLayout.CENTER);
// Create ActionListener
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
JFileChooser theFileChooser = (JFileChooser)actionEvent.getSource();
String command = actionEvent.getActionCommand();
if (command.equals(JFileChooser.APPROVE_SELECTION)) {
File selectedFile = theFileChooser.getSelectedFile();
directoryLabel.setText(selectedFile.getParent());
filenameLabel.setText(selectedFile.getName());
} else if (command.equals(JFileChooser.CANCEL_SELECTION)) {
directoryLabel.setText(" ");
filenameLabel.setText(" ");
}
}
};
fileChooser.addActionListener(actionListener);
frame.pack();
frame.setVisible(true);
}
}
Adding Accessory Panels
The accessory component can enhance the functionality of the chooser, including previewing an image or document, or playing an audio file.
To respond to file selection changes, the accessory component should attach itself as a PropertyChangeListener to the JFileChooser.
import java.awt.Dimension;
import java.awt.Image;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
class LabelAccessory extends JLabel implements PropertyChangeListener {
private static final int PREFERRED_WIDTH = 125;
private static final int PREFERRED_HEIGHT = 100;
public LabelAccessory(JFileChooser chooser) {
setVerticalAlignment(JLabel.CENTER);
setHorizontalAlignment(JLabel.CENTER);
chooser.addPropertyChangeListener(this);
setPreferredSize(new Dimension(PREFERRED_WIDTH, PREFERRED_HEIGHT));
}
public void propertyChange(PropertyChangeEvent changeEvent) {
String changeName = changeEvent.getPropertyName();
if (changeName.equals(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)) {
File file = (File)changeEvent.getNewValue();
if (file != null) {
ImageIcon icon = new ImageIcon(file.getPath());
if (icon.getIconWidth() > PREFERRED_WIDTH) {
icon = new ImageIcon(icon.getImage().getScaledInstance(
PREFERRED_WIDTH, -1, Image.SCALE_DEFAULT));
if (icon.getIconHeight() > PREFERRED_HEIGHT) {
icon = new ImageIcon(icon.getImage().getScaledInstance(
-1, PREFERRED_HEIGHT, Image.SCALE_DEFAULT));
}
}
setIcon(icon);
}
}
}
}
public class JFileChooserAddingAccessoryPanels {
public static void main(String[] a){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAccessory(new LabelAccessory(fileChooser));
fileChooser.showOpenDialog(null);
}
}
Adding a Filter to a File Chooser Dialog
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser fileChooser = new JFileChooser(new File("."));
fileChooser.addChoosableFileFilter(new MyFilter());
fileChooser.showOpenDialog(null);
System.out.println(fileChooser.getSelectedFile());
}
}
class MyFilter extends javax.swing.filechooser.FileFilter {
public boolean accept(File file) {
String filename = file.getName();
return filename.endsWith(".java");
}
public String getDescription() {
return "*.java";
}
}
Adding an ActionListener to a JFileChooser to listen for selection of the approval or cancel actions.
- Approval is double-clicking a file, JFileChooser.APPROVE_SELECTION.
- Cancel is pressing the Escape key, JFileChooser.CANCEL_SELECTION.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JFileChooser;
public class JFileChooserSelectionOption {
public static void main(String[] a) {
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Action");
}
});
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getParent());
System.out.println(selectedFile.getName());
} else if (status == JFileChooser.CANCEL_OPTION) {
System.out.println("calceled");
}
}
}
Changing the Text of the Approve Button in a JFileChooser Dialog
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
// Set the text
chooser.setApproveButtonText("New Approve Text");
// Set the mnemonic
chooser.setApproveButtonMnemonic("a");
// Set the tool tip
chooser.setApproveButtonToolTipText("New Approve Tool Tip");
chooser.showOpenDialog(null);
}
}
Creating a JFileChooser Dialog
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
String filename = File.separator + "tmp";
JFileChooser fc = new JFileChooser(new File(filename));
// Show open dialog
fc.showOpenDialog(null);
File selFile = fc.getSelectedFile();
// Show save dialog
fc.showSaveDialog(null);
selFile = fc.getSelectedFile();
}
}
Custom FileView for Some Java-Related File Types
FileView is the area where all the file names are listed.
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileView;
class JavaFileView extends FileView {
Icon jarIcon = new ImageIcon("yourFile.gif");
public String getName(File file) {
String filename = file.getName();
if (filename.endsWith(".java")) {
String name = filename + " : " + file.length();
return name;
}
return null;
}
public String getTypeDescription(File file) {
String typeDescription = null;
String filename = file.getName().toLowerCase();
if (filename.endsWith(".java") || filename.endsWith(".class")) {
typeDescription = "Java Source";
}
return typeDescription;
}
public Icon getIcon(File file) {
if (file.isDirectory()) {
return null;
}
Icon icon = null;
String filename = file.getName().toLowerCase();
if (filename.endsWith(".java") || filename.endsWith(".class")) {
icon = jarIcon;
}
return icon;
}
}
public class UsingFileView {
public static void main(String[] a){
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileView(new JavaFileView());
fileChooser.showOpenDialog(null);
}
}
Customizing a JFileChooser Look and Feel
Property StringObject TypeFileChooser.acceptAllFileFilterTextStringFileChooser.ancestorInputMapInputMapFileChooser.cancelButtonMnemonicIntegerFileChooser.cancelButtonTextStringFileChooser.cancelButtonToolTipTextStringFileChooser.deleteFileButtonMnemonicIntegerFileChooser.deleteFileButtonTextStringFileChooser.deleteFileButtonToolTipTextStringFileChooser.detailsViewButtonAccessibleNameStringFileChooser.detailsViewButtonToolTipTextStringFileChooser.detailsViewIconIconFileChooser.directoryDescriptionTextStringFileChooser.directoryOpenButtonMnemonicIntegerFileChooser.directoryOpenButtonTextStringFileChooser.directoryOpenButtonToolTipTextStringFileChooser.enterFilenameLabelMnemonicIntegerFileChooser.enterFilenameLabelTextStringFileChooser.fileDescriptionTextStringFileChooser.fileNameLabelMnemonicIntegerFileChooser.fileNameLabelTextStringFileChooser.filesLabelMnemonicIntegerFileChooser.filesLabelTextStringFileChooser.filesOfTypeLabelMnemonicIntegerFileChooser.filesOfTypeLabelTextStringFileChooser.filterLabelMnemonicIntegerFileChooser.filterLabelTextStringFileChooser.foldersLabelMnemonicIntegerFileChooser.foldersLabelTextStringFileChooser.helpButtonMnemonicIntegerFileChooser.helpButtonTextStringFileChooser.helpButtonToolTipTextStringFileChooser.homeFolderAccessibleNameStringFileChooser.homeFolderIconIconFileChooser.homeFolderToolTipTextStringFileChooser.listFontFontFileChooser.listViewBackgroundColorFileChooser.listViewBorderBorderFileChooser.listViewButtonAccessibleNameStringFileChooser.listViewButtonToolTipTextStringFileChooser.listViewIconIconFileChooser.listViewWindowsStyleBooleanFileChooser.lookInLabelMnemonicIntegerFileChooser.lookInLabelTextStringFileChooser.newFolderAccessibleNameStringFileChooser.newFolderButtonMnemonicIntegerFileChooser.newFolderButtonTextStringFileChooser.newFolderButtonToolTipTextStringFileChooser.newFolderDialogTextStringFileChooser.newFolderErrorSeparatorStringFileChooser.newFolderErrorTextStringFileChooser.newFolderIconIconFileChooser.newFolderToolTipTextStringFileChooser.openButtonMnemonicIntegerFileChooser.openButtonTextStringFileChooser.openButtonToolTipTextStringFileChooser.openDialogTitleTextStringFileChooser.other.newFolderStringFileChooser.other.newFolder.subsequentStringFileChooser.win32.newFolderStringFileChooser.win32.newFolder.subsequentStringFileChooser.pathLabelMnemonicIntegerFileChooser.pathLabelTextStringFileChooser.readOnlyBooleanFileChooser.renameFileButtonMnemonicIntegerFileChooser.renameFileButtonTextStringFileChooser.renameFileButtonToolTipTextStringFileChooser.renameFileDialogTextStringFileChooser.renameFileErrorTextStringFileChooser.renameFileErrorTitleStringFileChooser.saveButtonMnemonicIntegerFileChooser.saveButtonTextStringFileChooser.saveButtonToolTipTextStringFileChooser.saveDialogTitleTextStringFileChooser.saveInLabelTextStringFileChooser.updateButtonMnemonicIntegerFileChooser.updateButtonTextStringFileChooser.updateButtonToolTipTextStringFileChooser.upFolderAccessibleNameStringFileChooser.upFolderIconIconFileChooser.upFolderToolTipTextStringFileChooser.usesSingleFilePaneBooleanFileChooser.useSystemExtensionHidingBooleanFileChooserUIStringFileView.ruputerIconIconFileView.directoryIconIconFileView.fileIconIconFileView.floppyDriveIconIconFileView.hardDriveIconIcon
Determining If a File Is Hidden
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
File file = new File("c:\\Program Files");
file = new File("c:\\IO.SYS");
boolean isHidden = chooser.getFileSystemView().isHiddenFile(file);
}
}
Determining If the Approve or Cancel Button Was Clicked in a JFileChooser Dialog
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
switch (result) {
case JFileChooser.APPROVE_OPTION:
System.out.println("Approve (Open or Save) was clicked");
break;
case JFileChooser.CANCEL_OPTION:
System.out.println("Cancel or the close-dialog icon was clicked");
break;
case JFileChooser.ERROR_OPTION:
System.out.println("Error");
break;
}
}
}
Disable the JFileChooser "New folder" button
import java.awt.ruponent;
import java.awt.Container;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
public class Main {
public static void disableNewFolderButton(Container c) {
int len = c.getComponentCount();
for (int i = 0; i < len; i++) {
Component comp = c.getComponent(i);
if (comp instanceof JButton) {
JButton b = (JButton) comp;
Icon icon = b.getIcon();
if (icon != null
&& icon == UIManager.getIcon("FileChooser.newFolderIcon"))
b.setEnabled(false);
} else if (comp instanceof Container) {
disableNewFolderButton((Container) comp);
}
}
}
public static void main(String s[]) {
JFileChooser chooser = new JFileChooser();
disableNewFolderButton(chooser);
int rc = chooser.showOpenDialog(null);
}
}
Displaying Only Directories in a File Chooser Dialog
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
}
}
Enabling Multiple Selections in a JFileChooser Dialog
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(true);
chooser.showOpenDialog(null);
File[] files = chooser.getSelectedFiles();
}
}
Get Directory Choice
/*
* Enhydra Java Application Server Project
*
* The contents of this file are subject to the Enhydra Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License on
* the gEnhydra web site ( http://www.enhydra.org/ ).
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific terms governing rights and limitations
* under the License.
*
* The Initial Developer of the Enhydra Application Server is Lutris
* Technologies, Inc. The Enhydra Application Server and portions created
* by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
* All Rights Reserved.
*
* Contributor(s):
* Paul Mahar
* Thomas Wessell
*
*/
//
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.util.ResourceBundle;
/**
* SwingUtil contains static utility methods for working with Swing
* classes.
*
*/
public class SwingUtil {
/**
* Hidden default constructor
*/
private SwingUtil() {}
/**
* Open a JFileChooser dialog for selecting a directory and return the
* selected directory.
*
* @param owner
* The frame or dialog that controls the invokation of this dialog.
* @param defaultDir
* A string representation of the directory to show when the
* dialog opens.
* @param title
* Tile for the dialog.
*
* @return
* The selected directory as a File. Null if user cancels dialog without
* a selection.
*
*/
public static File getDirectoryChoice(Component owner, String defaultDir,
String title) {
return getDirectoryChoice(owner, new File(defaultDir), title);
}
/**
* Open a JFileChooser dialog for selecting a directory and return the
* selected directory.
*
*
* @param owner
* The frame or dialog that controls the invokation of this dialog.
* @param defaultDir
* The directory to show when the dialog opens.
* @param title
* Tile for the dialog.
*
* @return
* The selected directory as a File. Null if user cancels dialog without
* a selection.
*
*/
public static File getDirectoryChoice(Component owner, File defaultDir,
String title) {
//
// There is apparently a bug in the native Windows FileSystem class that
// occurs when you use a file chooser and there is a security manager
// active. An error dialog is displayed indicating there is no disk in
// Drive A:. To avoid this, the security manager is temporarily set to
// null and then reset after the file chooser is closed.
//
SecurityManager sm = null;
JFileChooser chooser = null;
File choice = null;
sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if ((defaultDir != null) && defaultDir.exists()
&& defaultDir.isDirectory()) {
chooser.setCurrentDirectory(defaultDir);
chooser.setSelectedFile(defaultDir);
}
chooser.setDialogTitle(title);
chooser.setApproveButtonText("OK");
int v = chooser.showOpenDialog(owner);
owner.requestFocus();
switch (v) {
case JFileChooser.APPROVE_OPTION:
if (chooser.getSelectedFile() != null) {
if (chooser.getSelectedFile().exists()) {
choice = chooser.getSelectedFile();
} else {
File parentFile =
new File(chooser.getSelectedFile().getParent());
choice = parentFile;
}
}
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
return choice;
}
/**
* Get a file selection using the FileChooser dialog.
*
* @param owner
* The parent of this modal dialog.
* @param defaultSelection
* The default file selection as a string.
* @param filter
* An extension filter
* @param title
* The caption for the dialog.
*
* @return
* A selected file or null if no selection is made.
*/
public static File getFileChoice(Component owner,
String defaultSelection,
FileFilter filter, String title) {
return SwingUtil.getFileChoice(owner, new File(defaultSelection),
filter, title);
}
/**
* Get a file selection using the FileChooser dialog.
*
* @param owner
* The parent of this modal dialog.
* @param defaultSelection
* The default file selection as a file.
* @param filter
* An extension filter
* @param title
* The caption for the dialog.
*
* @return
* A selected file or null if no selection is made.
*/
public static File getFileChoice(Component owner, File defaultSelection,
FileFilter filter, String title) {
//
// There is apparently a bug in the native Windows FileSystem class that
// occurs when you use a file chooser and there is a security manager
// active. An error dialog is displayed indicating there is no disk in
// Drive A:. To avoid this, the security manager is temporarily set to
// null and then reset after the file chooser is closed.
//
SecurityManager sm = null;
File choice = null;
JFileChooser chooser = null;
sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
if (defaultSelection.isDirectory()) {
chooser.setCurrentDirectory(defaultSelection);
} else {
chooser.setSelectedFile(defaultSelection);
}
chooser.setFileFilter(filter);
chooser.setDialogTitle(title);
chooser.setApproveButtonText("OK");
int v = chooser.showOpenDialog(owner);
owner.requestFocus();
switch (v) {
case JFileChooser.APPROVE_OPTION:
if (chooser.getSelectedFile() != null) {
choice = chooser.getSelectedFile();
}
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
return choice;
}
/**
* Get the point on point on the screen at which to open a dialog
* or window for it to appear centered. This point is the top right hand
* corner of the container you want to position.
*
*
* @param size
* The demensions of the dialog or window to position.
*
* @return
* The top left hand point at which to position the container
* for it to appear centered.
*
*/
public static Point getCenteringPoint(Dimension size) {
Point centeringPoint = new Point();
Dimension screenSize;
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (size.height > screenSize.height) {
size.height = screenSize.height;
}
if (size.width > screenSize.width) {
size.width = screenSize.width;
}
centeringPoint.x = (screenSize.width - size.width) / 2;
centeringPoint.y = (screenSize.height - size.height) / 2;
return centeringPoint;
}
}
Get File Choice
/*
* Enhydra Java Application Server Project
*
* The contents of this file are subject to the Enhydra Public License
* Version 1.1 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License on
* the gEnhydra web site ( http://www.enhydra.org/ ).
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
* the License for the specific terms governing rights and limitations
* under the License.
*
* The Initial Developer of the Enhydra Application Server is Lutris
* Technologies, Inc. The Enhydra Application Server and portions created
* by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
* All Rights Reserved.
*
* Contributor(s):
* Paul Mahar
* Thomas Wessell
*
*/
//
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.ruponent;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.io.File;
import javax.swing.filechooser.FileFilter;
import java.util.ResourceBundle;
/**
* SwingUtil contains static utility methods for working with Swing
* classes.
*
*/
public class SwingUtil {
/**
* Hidden default constructor
*/
private SwingUtil() {}
/**
* Open a JFileChooser dialog for selecting a directory and return the
* selected directory.
*
* @param owner
* The frame or dialog that controls the invokation of this dialog.
* @param defaultDir
* A string representation of the directory to show when the
* dialog opens.
* @param title
* Tile for the dialog.
*
* @return
* The selected directory as a File. Null if user cancels dialog without
* a selection.
*
*/
public static File getDirectoryChoice(Component owner, String defaultDir,
String title) {
return getDirectoryChoice(owner, new File(defaultDir), title);
}
/**
* Open a JFileChooser dialog for selecting a directory and return the
* selected directory.
*
*
* @param owner
* The frame or dialog that controls the invokation of this dialog.
* @param defaultDir
* The directory to show when the dialog opens.
* @param title
* Tile for the dialog.
*
* @return
* The selected directory as a File. Null if user cancels dialog without
* a selection.
*
*/
public static File getDirectoryChoice(Component owner, File defaultDir,
String title) {
//
// There is apparently a bug in the native Windows FileSystem class that
// occurs when you use a file chooser and there is a security manager
// active. An error dialog is displayed indicating there is no disk in
// Drive A:. To avoid this, the security manager is temporarily set to
// null and then reset after the file chooser is closed.
//
SecurityManager sm = null;
JFileChooser chooser = null;
File choice = null;
sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
if ((defaultDir != null) && defaultDir.exists()
&& defaultDir.isDirectory()) {
chooser.setCurrentDirectory(defaultDir);
chooser.setSelectedFile(defaultDir);
}
chooser.setDialogTitle(title);
chooser.setApproveButtonText("OK");
int v = chooser.showOpenDialog(owner);
owner.requestFocus();
switch (v) {
case JFileChooser.APPROVE_OPTION:
if (chooser.getSelectedFile() != null) {
if (chooser.getSelectedFile().exists()) {
choice = chooser.getSelectedFile();
} else {
File parentFile =
new File(chooser.getSelectedFile().getParent());
choice = parentFile;
}
}
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
return choice;
}
/**
* Get a file selection using the FileChooser dialog.
*
* @param owner
* The parent of this modal dialog.
* @param defaultSelection
* The default file selection as a string.
* @param filter
* An extension filter
* @param title
* The caption for the dialog.
*
* @return
* A selected file or null if no selection is made.
*/
public static File getFileChoice(Component owner,
String defaultSelection,
FileFilter filter, String title) {
return SwingUtil.getFileChoice(owner, new File(defaultSelection),
filter, title);
}
/**
* Get a file selection using the FileChooser dialog.
*
* @param owner
* The parent of this modal dialog.
* @param defaultSelection
* The default file selection as a file.
* @param filter
* An extension filter
* @param title
* The caption for the dialog.
*
* @return
* A selected file or null if no selection is made.
*/
public static File getFileChoice(Component owner, File defaultSelection,
FileFilter filter, String title) {
//
// There is apparently a bug in the native Windows FileSystem class that
// occurs when you use a file chooser and there is a security manager
// active. An error dialog is displayed indicating there is no disk in
// Drive A:. To avoid this, the security manager is temporarily set to
// null and then reset after the file chooser is closed.
//
SecurityManager sm = null;
File choice = null;
JFileChooser chooser = null;
sm = System.getSecurityManager();
System.setSecurityManager(null);
chooser = new JFileChooser();
if (defaultSelection.isDirectory()) {
chooser.setCurrentDirectory(defaultSelection);
} else {
chooser.setSelectedFile(defaultSelection);
}
chooser.setFileFilter(filter);
chooser.setDialogTitle(title);
chooser.setApproveButtonText("OK");
int v = chooser.showOpenDialog(owner);
owner.requestFocus();
switch (v) {
case JFileChooser.APPROVE_OPTION:
if (chooser.getSelectedFile() != null) {
choice = chooser.getSelectedFile();
}
break;
case JFileChooser.CANCEL_OPTION:
case JFileChooser.ERROR_OPTION:
}
chooser.removeAll();
chooser = null;
System.setSecurityManager(sm);
return choice;
}
/**
* Get the point on point on the screen at which to open a dialog
* or window for it to appear centered. This point is the top right hand
* corner of the container you want to position.
*
*
* @param size
* The demensions of the dialog or window to position.
*
* @return
* The top left hand point at which to position the container
* for it to appear centered.
*
*/
public static Point getCenteringPoint(Dimension size) {
Point centeringPoint = new Point();
Dimension screenSize;
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
if (size.height > screenSize.height) {
size.height = screenSize.height;
}
if (size.width > screenSize.width) {
size.width = screenSize.width;
}
centeringPoint.x = (screenSize.width - size.width) / 2;
centeringPoint.y = (screenSize.height - size.height) / 2;
return centeringPoint;
}
}
Getting and Setting the Current Directory of a JFileChooser Dialog
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception {
JFileChooser chooser = new JFileChooser();
File f = new File(new File(".").getCanonicalPath());
chooser.setCurrentDirectory(f);
chooser.setCurrentDirectory(null);
chooser.showOpenDialog(null);
File curDir = chooser.getCurrentDirectory();
}
}
Getting and Setting the Selected File of a JFileChooser Dialog
import java.io.File;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception{
JFileChooser chooser = new JFileChooser();
File f = new File(new File("filename.txt").getCanonicalPath());
chooser.setSelectedFile(f);
chooser.showOpenDialog(null);
File curFile = chooser.getSelectedFile();
}
}
Getting the File-Type Icon of a File
import java.awt.BorderLayout;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main {
public static void main(String[] argv) throws Exception {
JFileChooser chooser = new JFileChooser();
File file = new File("filename.txt");
Icon icon = chooser.getIcon(file);
JLabel label = new JLabel("" + file);
label.setIcon(icon);
JFrame frame = new JFrame();
frame.getContentPane().add(label, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Getting the Large File-Type Icon of a File
import java.io.File;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import sun.awt.shell.ShellFolder;
public class Main {
public static void main(String[] argv) throws Exception {
File file = new File("filename.txt");
ShellFolder sf = ShellFolder.getShellFolder(file);
Icon icon = new ImageIcon(sf.getIcon(true), sf.getFolderType());
}
}
JFileChooser
A JFileChooser is a dialog to select a file or files.
The return value of the three methods is one of the following:
- JFileChooser.CANCEL_OPTION, if the user clicks Cancel.
- JFileChooser.APPROVE_OPTION, if the user click an OK/Open/Save button.
- JFileChooser.ERROR_OPTION, if the user closes the dialog
A return value of JFileChooser.APPROVE_OPTION, indicates that you can call its getSelectedFile or getSelectedFiles methods:
public java.io.File getSelectedFile ()
public java.io.File[] getSelectedFiles ()
JFileChooser is a standard dialog for selecting a file from the file system.
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
public class FileChooserDialog {
public static void main(String[] args) {
JFileChooser fileopen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("c files", "c");
fileopen.addChoosableFileFilter(filter);
int ret = fileopen.showDialog(null, "Open file");
if (ret == JFileChooser.APPROVE_OPTION) {
File file = fileopen.getSelectedFile();
System.out.println(file);
}
}
}
JFileChooser Selection Option: JFileChooser.APPROVE_OPTION, JFileChooser.CANCEL_OPTION
import java.io.File;
import javax.swing.JFileChooser;
public class JFileChooserSelectionOption {
public static void main(String[] a) {
JFileChooser fileChooser = new JFileChooser(".");
int status = fileChooser.showOpenDialog(null);
if (status == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getParent());
System.out.println(selectedFile.getName());
} else if (status == JFileChooser.CANCEL_OPTION) {
System.out.println("canceled");
}
}
}
Listening for Approve and Cancel Events in a JFileChooser Dialog
import java.awt.ruponent;
import java.awt.HeadlessException;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.AbstractAction;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) throws Exception {
MyFileChooser chooser = new MyFileChooser();
chooser.setDialogType(JFileChooser.SAVE_DIALOG);
final JDialog dialog = chooser.createDialog(null);
chooser.addActionListener(new AbstractAction() {
public void actionPerformed(ActionEvent evt) {
JFileChooser chooser = (JFileChooser) evt.getSource();
if (JFileChooser.APPROVE_SELECTION.equals(evt.getActionCommand())) {
dialog.setVisible(false);
} else if (JFileChooser.CANCEL_SELECTION.equals(evt.getActionCommand())) {
dialog.setVisible(false);
}
}
});
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialog.setVisible(false);
}
});
dialog.setVisible(true);
}
}
class MyFileChooser extends JFileChooser {
public JDialog createDialog(Component parent) throws HeadlessException {
return super.createDialog(parent);
}
}
Listening for Changes to the Selected File in a JFileChooser Dialog
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.Arrays;
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
chooser.addPropertyChangeListener(new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File oldFile = (File) evt.getOldValue();
File newFile = (File) evt.getNewValue();
System.out.println(oldFile);
System.out.println(newFile);
System.out.println(chooser.getSelectedFile());
} else if (JFileChooser.SELECTED_FILES_CHANGED_PROPERTY.equals(evt.getPropertyName())) {
JFileChooser chooser = (JFileChooser) evt.getSource();
File[] oldFiles = (File[]) evt.getOldValue();
File[] newFiles = (File[]) evt.getNewValue();
Arrays.toString(oldFiles);
Arrays.toString(newFiles);
File[] files = chooser.getSelectedFiles();
Arrays.toString(files);
}
}
});
chooser.setVisible(true);
}
}
Localize a JFileChooser
[JFileChooser_en.properties]
Title=JFileChooser
lookInLabelText=Current
filesOfTypeLabelText=File type
upFolderToolTipText=go up
[JFileChooser_fr.properties]
Title=JFileChooser de R\u00e9al
lookInLabelText=Courant
filesOfTypeLabelText=Type de fichier
upFolderToolTipText=Remonte
/*
FileChooser.fileNameLabelText
FileChooser.homeFolderToolTipText
FileChooser.newFolderToolTipText
FileChooser.listViewButtonToolTipTextlist
FileChooser.detailsViewButtonToolTipText
FileChooser.saveButtonText=Save
FileChooser.openButtonText=Open
FileChooser.cancelButtonText=Cancel
FileChooser.updateButtonText=Update
FileChooser.helpButtonText=Help
FileChooser.saveButtonToolTipText=Save
FileChooser.openButtonToolTipText=Open
FileChooser.cancelButtonToolTipText=Cancel
FileChooser.updateButtonToolTipText=Update
FileChooser.helpButtonToolTipText=Help
*/
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.UIManager;
public class Main {
public static void main(String[] argv) throws Exception {
Locale locale = Locale.getDefault();
ResourceBundle rb = ResourceBundle.getBundle("JFileChooser", locale);
UIManager.put("FileChooser.lookInLabelText", rb.getString("lookInLabelText"));
UIManager.put("FileChooser.filesOfTypeLabelText", rb.getString("filesOfTypeLabelText"));
UIManager.put("FileChooser.upFolderToolTipText", rb.getString("upFolderToolTipText"));
}
}
Select a directory with a JFileChooser
import javax.swing.JFileChooser;
public class Main {
public static void main(String s[]) {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("choosertitle");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
} else {
System.out.println("No Selection ");
}
}
}
Showing Hidden Files in a JFileChooser Dialog
import javax.swing.JFileChooser;
public class Main {
public static void main(String[] argv) {
JFileChooser chooser = new JFileChooser();
boolean hidingEnabled = chooser.isFileHidingEnabled();
chooser.setFileHidingEnabled(false);
chooser.showOpenDialog(null);
}
}
The JFileChooser supports three selection modes: files only, directories only, and files and directories
The fileSelectionMode property setting determines the mode of the chooser.
The available settings are specified by the three JFileChooser constants:
- FILES_ONLY,
- DIRECTORIES_ONLY, and
- FILES_AND_DIRECTORIES.
Initially, the file chooser is in JFileChooser.FILES_ONLY mode.
To change the mode, just call public void setFileSelectionMode(int newMode).
import javax.swing.JFileChooser;
public class JFileChooserSelectionMode {
public static void main(String[] a) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fileChooser.showOpenDialog(null);
}
}
import javax.swing.JFileChooser;
public class JFileChooserHidingFiles {
public static void main(String[] a) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileHidingEnabled(false);
fileChooser.showOpenDialog(null);
}
}
Using a JFileChooser in Your JFrame
import java.awt.BorderLayout;
import java.awt.Font;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class FileSamplePanel {
public static void main(String args[]) {
JFrame frame = new JFrame("JFileChooser Popup");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JLabel directoryLabel = new JLabel(" ");
directoryLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(directoryLabel, BorderLayout.NORTH);
final JLabel filenameLabel = new JLabel(" ");
filenameLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36));
frame.add(filenameLabel, BorderLayout.SOUTH);
JFileChooser fileChooser = new JFileChooser(".");
fileChooser.setControlButtonsAreShown(false);
frame.add(fileChooser, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
Using JFileChooser
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
public class JFileChooserTest {
public static void main(String[] args) {
JFrame.setDefaultLookAndFeelDecorated(true);
JDialog.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("JComboBox Test");
frame.setLayout(new FlowLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button = new JButton("Select File");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
JFileChooser fileChooser = new JFileChooser();
int returnValue = fileChooser.showOpenDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File selectedFile = fileChooser.getSelectedFile();
System.out.println(selectedFile.getName());
}
}
});
frame.add(button);
frame.pack();
frame.setVisible(true);
}
}
Working with File Filters
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
class ExtensionFileFilter extends FileFilter {
String description;
String extensions[];
public ExtensionFileFilter(String description, String extension) {
this(description, new String[] { extension });
}
public ExtensionFileFilter(String description, String extensions[]) {
if (description == null) {
this.description = extensions[0] + "{ " + extensions.length + "} ";
} else {
this.description = description;
}
this.extensions = (String[]) extensions.clone();
toLower(this.extensions);
}
private void toLower(String array[]) {
for (int i = 0, n = array.length; i < n; i++) {
array[i] = array[i].toLowerCase();
}
}
public String getDescription() {
return description;
}
public boolean accept(File file) {
if (file.isDirectory()) {
return true;
} else {
String path = file.getAbsolutePath().toLowerCase();
for (int i = 0, n = extensions.length; i < n; i++) {
String extension = extensions[i];
if ((path.endsWith(extension) && (path.charAt(path.length() - extension.length() - 1)) == ".")) {
return true;
}
}
}
return false;
}
}
public class JFileChooserWithCustomizedFilter {
public static void main(String[] a) {
JFileChooser fileChooser = new JFileChooser(".");
FileFilter jpegFilter = new ExtensionFileFilter(null, new String[] { "JPG", "JPEG" });
fileChooser.addChoosableFileFilter(jpegFilter);
fileChooser.showOpenDialog(null);
}
}