Java/Swing JFC/File Chooser
Содержание
- 1 Adding a Filter to a File Chooser Dialog
- 2 A demo which makes extensive use of the file chooser
- 3 A simple file chooser to see what it takes to make one of these work
- 4 A simple FileFilter class that works by filename extension
- 5 Changing the Text of the Approve Button in a JFileChooser Dialog
- 6 Choose a File
- 7 Creating a JFileChooser Dialog
- 8 Customizing a JFileChooser
- 9 Demonstration of File dialog boxes
- 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"s "New folder" button
- 13 Displaying Only Directories in a File Chooser Dialog
- 14 Enabling Multiple Selections in a JFileChooser Dialog
- 15 extends FileView to create custom File chooser
- 16 Extension File Filter
- 17 FileChooser Demo
- 18 File Chooser Demo 2
- 19 File Chooser Demo 4
- 20 FileChooser file filter customized filechooser
- 21 Files filter that filters files by their suffix (or extension)
- 22 Generic File Filter
- 23 Get Directory Choice
- 24 Get File Choice
- 25 Getting and Setting the Current Directory of a JFileChooser Dialog
- 26 Getting and Setting the Selected File of a JFileChooser Dialog
- 27 Getting the File-Type Icon of a File
- 28 Getting the File-Type Name of a File
- 29 Getting the Large File-Type Icon of a File
- 30 JDialog javax.swing.JFileChooser.createDialog(Component parent)
- 31 JFileChooser class in action with an accessory
- 32 JFileChooser is a standard dialog for selecting a file from the file system.
- 33 Listening for Approve and Cancel Events in a JFileChooser Dialog
- 34 Listening for Changes to the Selected File in a JFileChooser Dialog
- 35 Localize a JFileChooser
- 36 see what it takes to make one of these filters work
- 37 Select a directory with a JFileChooser
- 38 Showing Hidden Files in a JFileChooser Dialog
- 39 show thumbnails of graphic files
- 40 String javax.swing.JFileChooser.APPROVE_SELECTION
- 41 Suffix FileFilter
- 42 Swing File Chooser Demo
- 43 Validate a filename from a JFileChooser
- 44 void javax.swing.JFileChooser.addActionListener(ActionListener l)
- 45 void javax.swing.JFileChooser.setDialogType(int dialogType)
Adding a Filter to a File Chooser Dialog
<source lang="java">
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"; }
}
</source>
A demo which makes extensive use of the file chooser
<source lang="java">
/*
* @(#)FileChooserDemo.java 1.31 06/02/03 * * Copyright (c) 2006 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: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce 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 MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS 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 THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
/*
* @(#)FileChooserDemo.java 1.31 06/02/03 */
import static javax.swing.JFileChooser.APPROVE_OPTION; import static javax.swing.JFileChooser.APPROVE_SELECTION; import static javax.swing.JFileChooser.CANCEL_OPTION; import static javax.swing.JFileChooser.CANCEL_SELECTION; import static javax.swing.JFileChooser.CUSTOM_DIALOG; import static javax.swing.JFileChooser.DIRECTORIES_ONLY; import static javax.swing.JFileChooser.ERROR_OPTION; import static javax.swing.JFileChooser.FILES_AND_DIRECTORIES; import static javax.swing.JFileChooser.FILES_ONLY; import static javax.swing.JFileChooser.OPEN_DIALOG; import static javax.swing.JFileChooser.SAVE_DIALOG; import static javax.swing.JFileChooser.SELECTED_FILE_CHANGED_PROPERTY; import java.awt.BorderLayout; import java.awt.CardLayout; import java.awt.ruponent; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.util.Hashtable; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.DefaultComboBoxModel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.LookAndFeel; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.filechooser.FileView; import javax.swing.plaf.FileChooserUI; import javax.swing.plaf.basic.BasicFileChooserUI; /**
* * A demo which makes extensive use of the file chooser. * * 1.31 02/03/06 * * @author Jeff Dinkins */
public class FileChooserDemo extends JPanel implements ActionListener {
static JFrame frame; Vector<SupportedLaF> supportedLaFs = new Vector(); static class SupportedLaF { String name; LookAndFeel laf; SupportedLaF(String name, LookAndFeel laf) { this.name = name; this.laf = laf; } public String toString() { return name; } } JButton showButton; JCheckBox showAllFilesFilterCheckBox; JCheckBox showImageFilesFilterCheckBox; JCheckBox showFullDescriptionCheckBox; JCheckBox useFileViewCheckBox; JCheckBox accessoryCheckBox; JCheckBox setHiddenCheckBox; JCheckBox useEmbedInWizardCheckBox; JCheckBox useControlsCheckBox; JCheckBox enableDragCheckBox; JRadioButton singleSelectionRadioButton; JRadioButton multiSelectionRadioButton; JRadioButton openRadioButton; JRadioButton saveRadioButton; JRadioButton customButton; JComboBox lafComboBox; JRadioButton justFilesRadioButton; JRadioButton justDirectoriesRadioButton; JRadioButton bothFilesAndDirectoriesRadioButton; JTextField customField; FileFilter jpgFilter, gifFilter, bothFilter; ExampleFileView fileView; JPanel buttonPanel; public final static Dimension hpad10 = new Dimension(10, 1); public final static Dimension vpad20 = new Dimension(1, 20); public final static Dimension vpad7 = new Dimension(1, 7); public final static Dimension vpad4 = new Dimension(1, 4); public final static Insets insets = new Insets(5, 10, 0, 10); FilePreviewer previewer; JFileChooser chooser; public FileChooserDemo() { UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels(); for (UIManager.LookAndFeelInfo lafInfo : installedLafs) { try { Class lnfClass = Class.forName(lafInfo.getClassName()); LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance()); if (laf.isSupportedLookAndFeel()) { String name = lafInfo.getName(); supportedLaFs.add(new SupportedLaF(name, laf)); } } catch (Exception e) { // If ANYTHING weird happens, don"t add it continue; } } setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); chooser = new JFileChooser(); previewer = new FilePreviewer(chooser); // Create Custom FileView fileView = new ExampleFileView();
// fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg")));
// fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif"))); // create a radio listener to listen to option changes OptionListener optionListener = new OptionListener(); // Create options openRadioButton = new JRadioButton("Open"); openRadioButton.setSelected(true); openRadioButton.addActionListener(optionListener); saveRadioButton = new JRadioButton("Save"); saveRadioButton.addActionListener(optionListener); customButton = new JRadioButton("Custom"); customButton.addActionListener(optionListener); customField = new JTextField(8) { public Dimension getMaximumSize() { return new Dimension(getPreferredSize().width, getPreferredSize().height); } }; customField.setText("Doit"); customField.setAlignmentY(JComponent.TOP_ALIGNMENT); customField.setEnabled(false); customField.addActionListener(optionListener); ButtonGroup group1 = new ButtonGroup(); group1.add(openRadioButton); group1.add(saveRadioButton); group1.add(customButton); // filter buttons showAllFilesFilterCheckBox = new JCheckBox("Show \"All Files\" Filter"); showAllFilesFilterCheckBox.addActionListener(optionListener); showAllFilesFilterCheckBox.setSelected(true); showImageFilesFilterCheckBox = new JCheckBox("Show JPG and GIF Filters"); showImageFilesFilterCheckBox.addActionListener(optionListener); showImageFilesFilterCheckBox.setSelected(false); accessoryCheckBox = new JCheckBox("Show Preview"); accessoryCheckBox.addActionListener(optionListener); accessoryCheckBox.setSelected(false); // more options setHiddenCheckBox = new JCheckBox("Show Hidden Files"); setHiddenCheckBox.addActionListener(optionListener); showFullDescriptionCheckBox = new JCheckBox("With File Extensions"); showFullDescriptionCheckBox.addActionListener(optionListener); showFullDescriptionCheckBox.setSelected(true); showFullDescriptionCheckBox.setEnabled(false); useFileViewCheckBox = new JCheckBox("Use FileView"); useFileViewCheckBox.addActionListener(optionListener); useFileViewCheckBox.setSelected(false); useEmbedInWizardCheckBox = new JCheckBox("Embed in Wizard"); useEmbedInWizardCheckBox.addActionListener(optionListener); useEmbedInWizardCheckBox.setSelected(false); useControlsCheckBox = new JCheckBox("Show Control Buttons"); useControlsCheckBox.addActionListener(optionListener); useControlsCheckBox.setSelected(true); enableDragCheckBox = new JCheckBox("Enable Dragging"); enableDragCheckBox.addActionListener(optionListener); // File or Directory chooser options ButtonGroup group3 = new ButtonGroup(); justFilesRadioButton = new JRadioButton("Just Select Files"); justFilesRadioButton.setSelected(true); group3.add(justFilesRadioButton); justFilesRadioButton.addActionListener(optionListener); justDirectoriesRadioButton = new JRadioButton("Just Select Directories"); group3.add(justDirectoriesRadioButton); justDirectoriesRadioButton.addActionListener(optionListener); bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories"); group3.add(bothFilesAndDirectoriesRadioButton); bothFilesAndDirectoriesRadioButton.addActionListener(optionListener); singleSelectionRadioButton = new JRadioButton("Single Selection", true); singleSelectionRadioButton.addActionListener(optionListener); multiSelectionRadioButton = new JRadioButton("Multi Selection"); multiSelectionRadioButton.addActionListener(optionListener); ButtonGroup group4 = new ButtonGroup(); group4.add(singleSelectionRadioButton); group4.add(multiSelectionRadioButton); // Create show button showButton = new JButton("Show FileChooser"); showButton.addActionListener(this); showButton.setMnemonic("s"); // Create laf combo box lafComboBox = new JComboBox(supportedLaFs); lafComboBox.setEditable(false); lafComboBox.addActionListener(optionListener); // ******************************************************** // ******************** Dialog Type *********************** // ******************************************************** JPanel control1 = new InsetPanel(insets); control1.setBorder(BorderFactory.createTitledBorder("Dialog Type")); control1.setLayout(new BoxLayout(control1, BoxLayout.Y_AXIS)); control1.add(Box.createRigidArea(vpad20)); control1.add(openRadioButton); control1.add(Box.createRigidArea(vpad7)); control1.add(saveRadioButton); control1.add(Box.createRigidArea(vpad7)); control1.add(customButton); control1.add(Box.createRigidArea(vpad4)); JPanel fieldWrapper = new JPanel(); fieldWrapper.setLayout(new BoxLayout(fieldWrapper, BoxLayout.X_AXIS)); fieldWrapper.setAlignmentX(Component.LEFT_ALIGNMENT); fieldWrapper.add(Box.createRigidArea(hpad10)); fieldWrapper.add(Box.createRigidArea(hpad10)); fieldWrapper.add(customField); control1.add(fieldWrapper); control1.add(Box.createRigidArea(vpad20)); control1.add(Box.createGlue()); // ******************************************************** // ***************** Filter Controls ********************** // ******************************************************** JPanel control2 = new InsetPanel(insets); control2.setBorder(BorderFactory.createTitledBorder("Filter Controls")); control2.setLayout(new BoxLayout(control2, BoxLayout.Y_AXIS)); control2.add(Box.createRigidArea(vpad20)); control2.add(showAllFilesFilterCheckBox); control2.add(Box.createRigidArea(vpad7)); control2.add(showImageFilesFilterCheckBox); control2.add(Box.createRigidArea(vpad4)); JPanel checkWrapper = new JPanel(); checkWrapper.setLayout(new BoxLayout(checkWrapper, BoxLayout.X_AXIS)); checkWrapper.setAlignmentX(Component.LEFT_ALIGNMENT); checkWrapper.add(Box.createRigidArea(hpad10)); checkWrapper.add(Box.createRigidArea(hpad10)); checkWrapper.add(showFullDescriptionCheckBox); control2.add(checkWrapper); control2.add(Box.createRigidArea(vpad20)); control2.add(Box.createGlue()); // ******************************************************** // ****************** Display Options ********************* // ******************************************************** JPanel control3 = new InsetPanel(insets); control3.setBorder(BorderFactory.createTitledBorder("Display Options")); control3.setLayout(new BoxLayout(control3, BoxLayout.Y_AXIS)); control3.add(Box.createRigidArea(vpad20)); control3.add(setHiddenCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useFileViewCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(accessoryCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useEmbedInWizardCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(useControlsCheckBox); control3.add(Box.createRigidArea(vpad7)); control3.add(enableDragCheckBox); control3.add(Box.createRigidArea(vpad20)); control3.add(Box.createGlue()); // ******************************************************** // ************* File & Directory Options ***************** // ******************************************************** JPanel control4 = new InsetPanel(insets); control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options")); control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS)); control4.add(Box.createRigidArea(vpad20)); control4.add(justFilesRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(justDirectoriesRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(bothFilesAndDirectoriesRadioButton); control4.add(Box.createRigidArea(vpad20)); control4.add(singleSelectionRadioButton); control4.add(Box.createRigidArea(vpad7)); control4.add(multiSelectionRadioButton); control4.add(Box.createRigidArea(vpad20)); control4.add(Box.createGlue()); // ******************************************************** // **************** Look & Feel Switch ******************** // ******************************************************** JPanel panel = new JPanel(); panel.add(new JLabel("Look and Feel: ")); panel.add(lafComboBox); panel.add(showButton); // ******************************************************** // ****************** Wrap "em all up ********************* // ******************************************************** JPanel wrapper = new JPanel(); wrapper.setLayout(new BoxLayout(wrapper, BoxLayout.X_AXIS)); add(Box.createRigidArea(vpad20)); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control1); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control2); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control3); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(control4); wrapper.add(Box.createRigidArea(hpad10)); wrapper.add(Box.createRigidArea(hpad10)); add(wrapper); add(Box.createRigidArea(vpad20)); add(panel); add(Box.createRigidArea(vpad20)); } public void actionPerformed(ActionEvent e) { if (customButton.isSelected()) { chooser.setApproveButtonText(customField.getText()); } if (chooser.isMultiSelectionEnabled()) { chooser.setSelectedFiles(null); } else { chooser.setSelectedFile(null); } // clear the preview from the previous display of the chooser JComponent accessory = chooser.getAccessory(); if (accessory != null) { ((FilePreviewer) accessory).loadImage(null); } if (useEmbedInWizardCheckBox.isSelected()) { WizardDialog wizard = new WizardDialog(frame, true); wizard.setVisible(true); wizard.dispose(); return; } int retval = chooser.showDialog(frame, null); if (retval == APPROVE_OPTION) { JOptionPane.showMessageDialog(frame, getResultString()); } else if (retval == CANCEL_OPTION) { JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen."); } else if (retval == ERROR_OPTION) { JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen."); } else { JOptionPane.showMessageDialog(frame, "Unknown operation occured."); } } private void resetFileFilters(boolean enableFilters, boolean showExtensionInDescription) { chooser.resetChoosableFileFilters(); if (enableFilters) { jpgFilter = createFileFilter("JPEG Compressed Image Files", showExtensionInDescription, "jpg"); gifFilter = createFileFilter("GIF Image Files", showExtensionInDescription, "gif"); bothFilter = createFileFilter("JPEG and GIF Image Files", showExtensionInDescription, "jpg", "gif"); chooser.addChoosableFileFilter(bothFilter); chooser.addChoosableFileFilter(jpgFilter); chooser.addChoosableFileFilter(gifFilter); } } private FileFilter createFileFilter(String description, boolean showExtensionInDescription, String... extensions) { if (showExtensionInDescription) { description = createFileNameFilterDescriptionFromExtensions(description, extensions); } return new FileNameExtensionFilter(description, extensions); } private String createFileNameFilterDescriptionFromExtensions(String description, String[] extensions) { String fullDescription = (description == null) ? "(" : description + " ("; // build the description from the extension list fullDescription += "." + extensions[0]; for (int i = 1; i < extensions.length; i++) { fullDescription += ", ."; fullDescription += extensions[i]; } fullDescription += ")"; return fullDescription; } class WizardDialog extends JDialog implements ActionListener { CardLayout cardLayout; JPanel cardPanel; JLabel messageLabel; JButton backButton, nextButton, closeButton; WizardDialog(JFrame frame, boolean modal) { super(frame, "Embedded JFileChooser Demo", modal); cardLayout = new CardLayout(); cardPanel = new JPanel(cardLayout); getContentPane().add(cardPanel, BorderLayout.CENTER); messageLabel = new JLabel("", JLabel.CENTER); cardPanel.add(chooser, "fileChooser"); cardPanel.add(messageLabel, "label"); cardLayout.show(cardPanel, "fileChooser"); chooser.addActionListener(this); JPanel buttonPanel = new JPanel(); backButton = new JButton("< Back"); nextButton = new JButton("Next >"); closeButton = new JButton("Close"); buttonPanel.add(backButton); buttonPanel.add(nextButton); buttonPanel.add(closeButton); getContentPane().add(buttonPanel, BorderLayout.SOUTH); backButton.setEnabled(false); getRootPane().setDefaultButton(nextButton); backButton.addActionListener(this); nextButton.addActionListener(this); closeButton.addActionListener(this); pack(); setLocationRelativeTo(frame); } public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); String cmd = evt.getActionCommand(); if (src == backButton) { back(); } else if (src == nextButton) { FileChooserUI ui = chooser.getUI(); if (ui instanceof BasicFileChooserUI) { // Workaround for bug 4528663. This is necessary to // pick up the contents of the file chooser text field. // This will trigger an APPROVE_SELECTION action. ((BasicFileChooserUI) ui).getApproveSelectionAction().actionPerformed(null); } else { next(); } } else if (src == closeButton) { close(); } else if (cmd == APPROVE_SELECTION) { next(); } else if (cmd == CANCEL_SELECTION) { close(); } } private void back() { backButton.setEnabled(false); nextButton.setEnabled(true); cardLayout.show(cardPanel, "fileChooser"); getRootPane().setDefaultButton(nextButton); chooser.requestFocus(); } private void next() { backButton.setEnabled(true); nextButton.setEnabled(false); messageLabel.setText(getResultString()); cardLayout.show(cardPanel, "label"); getRootPane().setDefaultButton(closeButton); closeButton.requestFocus(); } private void close() { setVisible(false); } public void dispose() { chooser.removeActionListener(this); // The chooser is hidden by CardLayout on remove // so fix it here cardPanel.remove(chooser); chooser.setVisible(true); super.dispose(); } } private String getResultString() { String resultString = null; String filter = chooser.getFileFilter().getDescription(); String path = null; boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY); boolean isMulti = chooser.isMultiSelectionEnabled(); if (isMulti) { File[] files = chooser.getSelectedFiles(); if (files != null && files.length > 0) { path = ""; for (int i = 0; i < files.length; i++) { path = path + "
" + files[i].getPath(); } } } else { File file = chooser.getSelectedFile(); if (file != null) { path = "
" + file.getPath(); } } if (path != null) { path = path.replace(" ", " "); filter = filter.replace(" ", " "); resultString = "<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti ? "directories" : "directory") : (isMulti ? "files" : "file")) + ":" + path + "
with filter:" + filter; } else { resultString = "Nothing was chosen"; } return resultString; } /** An ActionListener that listens to the radio buttons. */ class OptionListener implements ActionListener { public void actionPerformed(ActionEvent e) { JComponent c = (JComponent) e.getSource(); boolean selected = false; if (c instanceof JToggleButton) { selected = ((JToggleButton) c).isSelected(); } if (c == openRadioButton) { chooser.setDialogType(OPEN_DIALOG); customField.setEnabled(false); repaint(); } else if (c == useEmbedInWizardCheckBox) { useControlsCheckBox.setEnabled(!selected); useControlsCheckBox.setSelected(!selected); chooser.setControlButtonsAreShown(!selected); } else if (c == useControlsCheckBox) { chooser.setControlButtonsAreShown(selected); } else if (c == enableDragCheckBox) { chooser.setDragEnabled(selected); } else if (c == saveRadioButton) { chooser.setDialogType(SAVE_DIALOG); customField.setEnabled(false); repaint(); } else if (c == customButton || c == customField) { customField.setEnabled(true); chooser.setDialogType(CUSTOM_DIALOG); repaint(); } else if (c == showAllFilesFilterCheckBox) { chooser.setAcceptAllFileFilterUsed(selected); } else if (c == showImageFilesFilterCheckBox) { resetFileFilters(selected, showFullDescriptionCheckBox.isSelected()); showFullDescriptionCheckBox.setEnabled(selected); } else if (c == setHiddenCheckBox) { chooser.setFileHidingEnabled(!selected); } else if (c == accessoryCheckBox) { if (selected) { chooser.setAccessory(previewer); } else { chooser.setAccessory(null); } } else if (c == useFileViewCheckBox) { if (selected) { chooser.setFileView(fileView); } else { chooser.setFileView(null); } } else if (c == showFullDescriptionCheckBox) { resetFileFilters(showImageFilesFilterCheckBox.isSelected(), selected); } else if (c == justFilesRadioButton) { chooser.setFileSelectionMode(FILES_ONLY); } else if (c == justDirectoriesRadioButton) { chooser.setFileSelectionMode(DIRECTORIES_ONLY); } else if (c == bothFilesAndDirectoriesRadioButton) { chooser.setFileSelectionMode(FILES_AND_DIRECTORIES); } else if (c == singleSelectionRadioButton) { if (selected) { chooser.setMultiSelectionEnabled(false); } } else if (c == multiSelectionRadioButton) { if (selected) { chooser.setMultiSelectionEnabled(true); } } else if (c == lafComboBox) { SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.getSelectedItem()); LookAndFeel laf = supportedLaF.laf; try { UIManager.setLookAndFeel(laf); SwingUtilities.updateComponentTreeUI(frame); if (chooser != null) { SwingUtilities.updateComponentTreeUI(chooser); } frame.pack(); } catch (UnsupportedLookAndFeelException exc) { // This should not happen because we already checked ((DefaultComboBoxModel) lafComboBox.getModel()).removeElement(supportedLaF); } } } } class FilePreviewer extends JComponent implements PropertyChangeListener { ImageIcon thumbnail = null; public FilePreviewer(JFileChooser fc) { setPreferredSize(new Dimension(100, 50)); fc.addPropertyChangeListener(this); } public void loadImage(File f) { if (f == null) { thumbnail = null; } else { ImageIcon tmpIcon = new ImageIcon(f.getPath()); if (tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); } else { thumbnail = tmpIcon; } } } public void propertyChange(PropertyChangeEvent e) { String prop = e.getPropertyName(); if (prop == SELECTED_FILE_CHANGED_PROPERTY) { if (isShowing()) { loadImage((File) e.getNewValue()); repaint(); } } } public void paint(Graphics g) { if (thumbnail != null) { int x = getWidth() / 2 - thumbnail.getIconWidth() / 2; int y = getHeight() / 2 - thumbnail.getIconHeight() / 2; if (y < 0) { y = 0; } if (x < 5) { x = 5; } thumbnail.paintIcon(this, g, x, y); } } } public static void main(String s[]) { /* * NOTE: By default, the look and feel will be set to the Cross Platform * Look and Feel (which is currently Metal). The user may someday be able to * override the default via a system property. If you as the developer want * to be sure that a particular L&F is set, you can do so by calling * UIManager.setLookAndFeel(). For example, the first code snippet below * forcibly sets the UI to be the System Look and Feel. The second code * snippet forcibly sets the look and feel to the Cross Platform L&F. * * Snippet 1: try { * UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } * catch (Exception exc) { System.err.println("Error loading L&F: " + exc); } * * Snippet 2: try { * UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); } * catch (Exception exc) { System.err.println("Error loading L&F: " + exc); } */ FileChooserDemo panel = new FileChooserDemo(); frame = new JFrame("FileChooserDemo"); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.getContentPane().add("Center", panel); frame.pack(); frame.setVisible(true); } class InsetPanel extends JPanel { Insets i; InsetPanel(Insets i) { this.i = i; } public Insets getInsets() { return i; } } /** * A utility function that layers on top of the LookAndFeel"s * isSupportedLookAndFeel() method. Returns true if the LookAndFeel is * supported. Returns false if the LookAndFeel is not supported and/or if * there is any kind of error checking if the LookAndFeel is supported. * * The L&F menu will use this method to detemine whether the various L&F * options should be active or inactive. * */ protected boolean isAvailableLookAndFeel(String laf) { try { Class lnfClass = Class.forName(laf); LookAndFeel newLAF = (LookAndFeel) (lnfClass.newInstance()); return newLAF.isSupportedLookAndFeel(); } catch (Exception e) { // If ANYTHING weird happens, return false return false; } }
} /*
* @(#)ExampleFileView.java 1.18 05/11/30 * * Copyright (c) 2006 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: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce 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 MIDROSYSTEMS, INC. ("SUN") AND ITS * LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A * RESULT OF USING, MODIFYING OR DISTRIBUTING THIS 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 THIS SOFTWARE, EVEN IF SUN HAS * BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended for * use in the design, construction, operation or maintenance of any nuclear * facility. */
/*
* @(#)ExampleFileView.java 1.18 05/11/30 */
/**
* A convenience implementation of the FileView interface that manages name, * icon, traversable, and file type information. * * This this implemention will work well with file systems that use "dot" * extensions to indicate file type. For example: "picture.gif" as a gif image. * * If the java.io.File ever contains some of this information, such as file * type, icon, and hidden file inforation, this implementation may become * obsolete. At minimum, it should be rewritten at that time to use any new type * information provided by java.io.File * * Example: JFileChooser chooser = new JFileChooser(); fileView = new * ExampleFileView(); fileView.putIcon("jpg", new * ImageIcon("images/jpgIcon.jpg")); fileView.putIcon("gif", new * ImageIcon("images/gifIcon.gif")); chooser.setFileView(fileView); * * @version 1.18 11/30/05 * @author Jeff Dinkins */
class ExampleFileView extends FileView {
private Hashtable icons = new Hashtable(5); private Hashtable fileDescriptions = new Hashtable(5); private Hashtable typeDescriptions = new Hashtable(5); /** * The name of the file. Do nothing special here. Let the system file view * handle this. * * @see FileView#getName */ public String getName(File f) { return null; } /** * Adds a human readable description of the file. */ public void putDescription(File f, String fileDescription) { fileDescriptions.put(f, fileDescription); } /** * A human readable description of the file. * * @see FileView#getDescription */ public String getDescription(File f) { return (String) fileDescriptions.get(f); }; /** * Adds a human readable type description for files. Based on "dot" extension * strings, e.g: ".gif". Case is ignored. */ public void putTypeDescription(String extension, String typeDescription) { typeDescriptions.put(extension, typeDescription); } /** * Adds a human readable type description for files of the type of the passed * in file. Based on "dot" extension strings, e.g: ".gif". Case is ignored. */ public void putTypeDescription(File f, String typeDescription) { putTypeDescription(getExtension(f), typeDescription); } /** * A human readable description of the type of the file. * * @see FileView#getTypeDescription */ public String getTypeDescription(File f) { return (String) typeDescriptions.get(getExtension(f)); } /** * Convenience method that returns the "dot" extension for the given file. */ public String getExtension(File f) { String name = f.getName(); if (name != null) { int extensionIndex = name.lastIndexOf("."); if (extensionIndex < 0) { return null; } return name.substring(extensionIndex + 1).toLowerCase(); } return null; } /** * Adds an icon based on the file type "dot" extension string, e.g: ".gif". * Case is ignored. */ public void putIcon(String extension, Icon icon) { icons.put(extension, icon); } /** * Icon that reperesents this file. Default implementation returns null. You * might want to override this to return something more interesting. * * @see FileView#getIcon */ public Icon getIcon(File f) { Icon icon = null; String extension = getExtension(f); if (extension != null) { icon = (Icon) icons.get(extension); } return icon; } /** * Whether the directory is traversable or not. Generic implementation returns * true for all directories and special folders. * * You might want to subtype ExampleFileView to do somethimg more interesting, * such as recognize compound documents directories; in such a case you might * return a special icon for the directory that makes it look like a regular * document, and return false for isTraversable to not allow users to descend * into the directory. * * @see FileView#isTraversable */ public Boolean isTraversable(File f) { // if (some_reason) { // return Boolean.FALSE; // } return null; // Use default from FileSystemView };
}
</source>
A simple file chooser to see what it takes to make one of these work
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
//SimpleFileChooser.java //A simple file chooser to see what it takes to make one of these work. // import java.awt.Container; 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.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; public class SimpleFileChooser extends JFrame { public SimpleFileChooser() {
super("File Chooser Test Frame"); setSize(350, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); JButton saveButton = new JButton("Save"); JButton dirButton = new JButton("Pick Dir"); final JLabel statusbar = new JLabel("Output of your selection will go here"); // Create a file chooser that opens up as an Open dialog openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(true); int option = chooser.showOpenDialog(SimpleFileChooser.this); if (option == JFileChooser.APPROVE_OPTION) { File[] sf = chooser.getSelectedFiles(); String filelist = "nothing"; if (sf.length > 0) filelist = sf[0].getName(); for (int i = 1; i < sf.length; i++) { filelist += ", " + sf[i].getName(); } statusbar.setText("You chose " + filelist); } else { statusbar.setText("You canceled."); } } }); // Create a file chooser that opens up as a Save dialog saveButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); int option = chooser.showSaveDialog(SimpleFileChooser.this); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You saved " + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); // Create a file chooser that allows you to pick a directory // rather than a file dirButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int option = chooser.showOpenDialog(SimpleFileChooser.this); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You opened " + ((chooser.getSelectedFile()!=null)? chooser.getSelectedFile().getName():"nothing")); } else { statusbar.setText("You canceled."); } } }); c.add(openButton); c.add(saveButton); c.add(dirButton); c.add(statusbar);
} public static void main(String args[]) {
SimpleFileChooser sfc = new SimpleFileChooser(); sfc.setVisible(true);
} }
</source>
A simple FileFilter class that works by filename extension
<source lang="java">
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002. * All rights reserved. Software written by Ian F. Darwin and others. * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS"" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s, * pioneering role in inventing and promulgating (and standardizing) the Java * language and environment is gratefully acknowledged. * * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for * inventing predecessor languages C and C++ is also gratefully acknowledged. */
import java.io.File; import java.util.ArrayList; import java.util.Iterator; /**
* A simple FileFilter class that works by filename extension, like the one in * the JDK demo called ExampleFileFilter, which has been announced to be * supported in a future Swing release. */
public class JFileFilter extends javax.swing.filechooser.FileFilter {
protected String description; protected ArrayList exts = new ArrayList(); public void addType(String s) { exts.add(s); } /** Return true if the given file is accepted by this filter. */ public boolean accept(File f) { // Little trick: if you don"t do this, only directory names // ending in one of the extentions appear in the window. if (f.isDirectory()) { return true; } else if (f.isFile()) { Iterator it = exts.iterator(); while (it.hasNext()) { if (f.getName().endsWith((String) it.next())) return true; } } // A file that didn"t match, or a weirdo (e.g. UNIX device file?). return false; } /** Set the printable description of this filter. */ public void setDescription(String s) { description = s; } /** Return the printable description of this filter. */ public String getDescription() { return description; }
}
</source>
Changing the Text of the Approve Button in a JFileChooser Dialog
<source lang="java">
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); }
}
</source>
Choose a File
<source lang="java">
import java.io.File; import javax.swing.JFileChooser; import javax.swing.JFrame; public class FileFilterDemo {
public FileFilterDemo() { } public static void main(String[] args) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new javax.swing.filechooser.FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".gif") || f.isDirectory(); } public String getDescription() { return "GIF Images"; } }); int r = chooser.showOpenDialog(new JFrame()); if (r == JFileChooser.APPROVE_OPTION) { String name = chooser.getSelectedFile().getName(); System.out.println(name); } }
}
</source>
Creating a JFileChooser Dialog
<source lang="java">
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(); }
}
</source>
Customizing a JFileChooser
<source lang="java">
import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.HashMap; import javax.swing.Icon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileView; public class EnhancedFileTester extends JPanel {
class AnOvalIcon implements Icon { Color color; public AnOvalIcon(Color c) { color = c; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(color); g.fillOval(x, y, getIconWidth(), getIconHeight()); } public int getIconWidth() { return 10; } public int getIconHeight() { return 15; } } public class IconView extends FileView { private HashMap hash = new HashMap(); public IconView() { hash.put("htm", new AnOvalIcon(Color.RED)); hash.put("html", new AnOvalIcon(Color.GREEN)); hash.put("java", new AnOvalIcon(Color.BLUE)); } public String getName(File f) { String s = f.getName(); if (s.length() == 0) { s = f.getAbsolutePath(); } return s; } public String getDescription(File f) { return f.getName(); } public String getTypeDescription(File f) { return f.getAbsolutePath(); } public Icon getIcon(File f) { String path = f.getAbsolutePath(); int pos = path.lastIndexOf("."); if ((pos >= 0) && (pos < (path.length() - 1))) { String ext = path.substring(pos + 1).toLowerCase(); return (Icon) hash.get(ext); } return null; } public Boolean isTraversable(File file) { return (new Boolean(file.isDirectory())); } } public class ExtensionFilter extends FileFilter { private String extensions[]; private String description; public ExtensionFilter(String description, String extension) { this(description, new String[] { extension }); } public ExtensionFilter(String description, String extensions[]) { this.description = description; this.extensions = (String[]) extensions.clone(); } public boolean accept(File file) { if (file.isDirectory()) { return true; } int count = extensions.length; String path = file.getAbsolutePath(); for (int i = 0; i < count; i++) { String ext = extensions[i]; if (path.endsWith(ext) && (path.charAt(path.length() - ext.length()) == ".")) { return true; } } return false; } public String getDescription() { return (description == null ? extensions[0] : description); } } public EnhancedFileTester() { JButton jb = new JButton("Open File Viewer"); add(jb); ActionListener listener = new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser chooser = new JFileChooser("."); FileFilter type1 = new ExtensionFilter("Java source", ".java"); FileFilter type2 = new ExtensionFilter("Image files", new String[] { ".jpg", ".gif", "jpeg", "xbm" }); FileFilter type3 = new ExtensionFilter("HTML files", new String[] { ".htm", ".html" }); chooser.addChoosableFileFilter(type1); chooser.addChoosableFileFilter(type2); chooser.addChoosableFileFilter(type3); chooser.setFileFilter(type2); // Initial filter setting FileView view = new IconView(); chooser.setFileView(view); int status = chooser.showOpenDialog(EnhancedFileTester.this); if (status == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); System.out.println(f); } } }; jb.addActionListener(listener); } public static void main(String args[]) { JFrame f = new JFrame("Enhanced File Example"); JPanel j = new EnhancedFileTester(); f.getContentPane().add(j, BorderLayout.CENTER); f.setSize(300, 200); f.show(); }
}
</source>
Demonstration of File dialog boxes
<source lang="java">
// : c14:FileChooserTest.java // Demonstration of File dialog boxes. // From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002 // www.BruceEckel.ru. See copyright notice in CopyRight.txt. import java.awt.BorderLayout; import java.awt.Container; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class FileChooserTest extends JFrame {
private JTextField filename = new JTextField(), dir = new JTextField(); private JButton open = new JButton("Open"), save = new JButton("Save"); public FileChooserTest() { JPanel p = new JPanel(); open.addActionListener(new OpenL()); p.add(open); save.addActionListener(new SaveL()); p.add(save); Container cp = getContentPane(); cp.add(p, BorderLayout.SOUTH); dir.setEditable(false); filename.setEditable(false); p = new JPanel(); p.setLayout(new GridLayout(2, 1)); p.add(filename); p.add(dir); cp.add(p, BorderLayout.NORTH); } class OpenL implements ActionListener { public void actionPerformed(ActionEvent e) { JFileChooser c = new JFileChooser(); // Demonstrate "Open" dialog: int rVal = c.showOpenDialog(FileChooserTest.this); if (rVal == JFileChooser.APPROVE_OPTION) { filename.setText(c.getSelectedFile().getName()); dir.setText(c.getCurrentDirectory().toString()); } if (rVal == JFileChooser.CANCEL_OPTION) { filename.setText("You pressed cancel"); dir.setText(""); } } } class SaveL implements ActionListener { public void actionPerformed(ActionEvent e) { JFileChooser c = new JFileChooser(); // Demonstrate "Save" dialog: int rVal = c.showSaveDialog(FileChooserTest.this); if (rVal == JFileChooser.APPROVE_OPTION) { filename.setText(c.getSelectedFile().getName()); dir.setText(c.getCurrentDirectory().toString()); } if (rVal == JFileChooser.CANCEL_OPTION) { filename.setText("You pressed cancel"); dir.setText(""); } } } public static void main(String[] args) { run(new FileChooserTest(), 250, 110); } public static void run(JFrame frame, int width, int height) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(width, height); frame.setVisible(true); }
} ///:~
</source>
Determining If a File Is Hidden
<source lang="java">
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); }
}
</source>
Determining If the Approve or Cancel Button Was Clicked in a JFileChooser Dialog
<source lang="java">
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; } }
}
</source>
Disable the JFileChooser"s "New folder" button
<source lang="java">
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); }
}
</source>
Displaying Only Directories in a File Chooser Dialog
<source lang="java">
import javax.swing.JFileChooser; public class Main {
public static void main(String[] argv) { JFileChooser fileChooser = new JFileChooser("."); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); }
}
</source>
Enabling Multiple Selections in a JFileChooser Dialog
<source lang="java">
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(); }
}
</source>
extends FileView to create custom File chooser
<source lang="java">
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileView; /*
* FileChooserDemo2.java requires these files: * ImageFileView.java * ImageFilter.java * ImagePreview.java * Utils.java * images/jpgIcon.gif (required by ImageFileView.java) * images/gifIcon.gif (required by ImageFileView.java) * images/tiffIcon.gif (required by ImageFileView.java) * images/pngIcon.png (required by ImageFileView.java) */
public class FileChooserDemo2 extends JPanel implements ActionListener {
static private String newline = "\n"; private JTextArea log; private JFileChooser fc; public FileChooserDemo2() { super(new BorderLayout()); // Create the log first, because the action listener // needs to refer to it. log = new JTextArea(5, 20); log.setMargin(new Insets(5, 5, 5, 5)); log.setEditable(false); JScrollPane logScrollPane = new JScrollPane(log); JButton sendButton = new JButton("Attach..."); sendButton.addActionListener(this); add(sendButton, BorderLayout.PAGE_START); add(logScrollPane, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { // Set up the file chooser. if (fc == null) { fc = new JFileChooser(); // Add a custom file filter and disable the default // (Accept All) file filter. fc.addChoosableFileFilter(new ImageFilter()); fc.setAcceptAllFileFilterUsed(false); // Add custom icons for file types. fc.setFileView(new ImageFileView()); // Add the preview pane. fc.setAccessory(new ImagePreview(fc)); } // Show it. int returnVal = fc.showDialog(FileChooserDemo2.this, "Attach"); // Process the results. if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); log.append("Attaching file: " + file.getName() + "." + newline); } else { log.append("Attachment cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); // Reset the file chooser for the next time it"s shown. fc.setSelectedFile(null); } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event dispatch thread. */ private static void createAndShowGUI() { // Create and set up the window. JFrame frame = new JFrame("FileChooserDemo2"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add content to the window. frame.add(new FileChooserDemo2()); // Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { // Schedule a job for the event dispatch thread: // creating and showing this application"s GUI. SwingUtilities.invokeLater(new Runnable() { public void run() { // Turn off metal"s use of bold fonts UIManager.put("swing.boldMetal", Boolean.FALSE); createAndShowGUI(); } }); }
} /*
* Copyright (c) 1995 - 2008 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. * - Redistributions in binary form must reproduce 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 nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
class ImageFileView extends FileView {
ImageIcon jpgIcon = Utils.createImageIcon("images/jpgIcon.gif"); ImageIcon gifIcon = Utils.createImageIcon("images/gifIcon.gif"); ImageIcon tiffIcon = Utils.createImageIcon("images/tiffIcon.gif"); ImageIcon pngIcon = Utils.createImageIcon("images/pngIcon.png"); public String getName(File f) { return null; // let the L&F FileView figure this out } public String getDescription(File f) { return null; // let the L&F FileView figure this out } public Boolean isTraversable(File f) { return null; // let the L&F FileView figure this out } 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; } 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; }
} /*
* Copyright (c) 1995 - 2008 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. * - Redistributions in binary form must reproduce 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 nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
class ImageFilter extends FileFilter {
// Accept all directories and all gif, jpg, tiff, or png files. 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 description of this filter public String getDescription() { return "Just Images"; }
} /*
* Copyright (c) 1995 - 2008 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. * - Redistributions in binary form must reproduce 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 nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
class ImagePreview extends JComponent implements PropertyChangeListener {
ImageIcon thumbnail = null; File file = null; public ImagePreview(JFileChooser fc) { setPreferredSize(new Dimension(100, 50)); fc.addPropertyChangeListener(this); } public void loadImage() { if (file == null) { thumbnail = null; return; } // Don"t use createImageIcon (which is a wrapper for getResource) // because the image we"re trying to load is probably not one // of this program"s own resources. ImageIcon tmpIcon = new ImageIcon(file.getPath()); if (tmpIcon != null) { if (tmpIcon.getIconWidth() > 90) { thumbnail = new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT)); } else { // no need to miniaturize thumbnail = tmpIcon; } } } 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(); } } } protected void paintComponent(Graphics g) { if (thumbnail == null) { loadImage(); } if (thumbnail != null) { int x = getWidth() / 2 - thumbnail.getIconWidth() / 2; int y = getHeight() / 2 - thumbnail.getIconHeight() / 2; if (y < 0) { y = 0; } if (x < 5) { x = 5; } thumbnail.paintIcon(this, g, x, y); } }
} /*
* Copyright (c) 1995 - 2008 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. * - Redistributions in binary form must reproduce 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 nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */
/* Utils.java is used by FileChooserDemo2.java. */ 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; } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = Utils.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn"t find file: " + path); return null; } }
}
</source>
Extension File Filter
<source lang="java">
/*
* jMemorize - Learning made easy (and fun) - A Leitner flashcards tool * Copyright(C) 2004-2006 Riad Djemili * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 1, or (at your option) * any later version. * * This program 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 for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
import java.io.File; import javax.swing.filechooser.FileFilter; /**
* A sime file filter for file choosers. * * @author djemili */
public class ExtensionFileFilter extends FileFilter {
private String m_extension; private String m_description; public ExtensionFileFilter(String extension, String description) { m_extension = extension; m_description = description; } /* * @see javax.swing.filechooser.FileFilter */ public boolean accept(File f) { return f.isDirectory() || f.getName().endsWith(m_extension); } /* * @see javax.swing.filechooser.FileFilter */ public String getDescription() { return m_description; } public String getExtension() { return m_extension; }
}
</source>
FileChooser Demo
<source lang="java">
import java.awt.BorderLayout; import java.awt.Container; 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); Container contentPane = frame.getContentPane(); final JLabel directoryLabel = new JLabel(" "); directoryLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36)); contentPane.add(directoryLabel, BorderLayout.NORTH); final JLabel filenameLabel = new JLabel(" "); filenameLabel.setFont(new Font("Serif", Font.BOLD | Font.ITALIC, 36)); contentPane.add(filenameLabel, BorderLayout.SOUTH); JFileChooser fileChooser = new JFileChooser("."); fileChooser.setControlButtonsAreShown(false); contentPane.add(fileChooser, BorderLayout.CENTER); 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); }
}
</source>
File Chooser Demo 2
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.filechooser.FileView; public class FileSample {
public static void main(String args[]) { JFrame frame = new JFrame("JFileChooser Popup"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); final JLabel directoryLabel = new JLabel(); contentPane.add(directoryLabel, BorderLayout.NORTH); final JLabel filenameLabel = new JLabel(); contentPane.add(filenameLabel, BorderLayout.SOUTH); final JButton button = new JButton("Open FileChooser"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Component parent = (Component) actionEvent.getSource(); JFileChooser fileChooser = new JFileChooser("."); fileChooser.setAccessory(new LabelAccessory(fileChooser)); FileView view = new JavaFileView(); fileChooser.setFileView(view); int status = fileChooser.showOpenDialog(parent); if (status == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); directoryLabel.setText(selectedFile.getParent()); filenameLabel.setText(selectedFile.getName()); } else if (status == JFileChooser.CANCEL_OPTION) { directoryLabel.setText(" "); filenameLabel.setText(" "); } } }; button.addActionListener(actionListener); contentPane.add(button, BorderLayout.CENTER); frame.setSize(300, 200); frame.setVisible(true); }
} 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); } } }
} class JavaFileView extends FileView {
Icon javaIcon = new DiamondIcon(Color.blue); Icon classIcon = new DiamondIcon(Color.green); Icon htmlIcon = new DiamondIcon(Color.red); Icon jarIcon = new DiamondIcon(Color.pink); 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")) { typeDescription = "Java Source"; } else if (filename.endsWith(".class")) { typeDescription = "Java Class File"; } else if (filename.endsWith(".jar")) { typeDescription = "Java Archive"; } else if (filename.endsWith(".html") || filename.endsWith(".htm")) { typeDescription = "Applet Loader"; } return typeDescription; } public Icon getIcon(File file) { if (file.isDirectory()) { return null; } Icon icon = null; String filename = file.getName().toLowerCase(); if (filename.endsWith(".java")) { icon = javaIcon; } else if (filename.endsWith(".class")) { icon = classIcon; } else if (filename.endsWith(".jar")) { icon = jarIcon; } else if (filename.endsWith(".html") || filename.endsWith(".htm")) { icon = htmlIcon; } return icon; }
} class DiamondIcon implements Icon {
private Color color; private boolean selected; private int width; private int height; private Polygon poly; private static final int DEFAULT_WIDTH = 10; private static final int DEFAULT_HEIGHT = 10; public DiamondIcon(Color color) { this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected) { this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected, int width, int height) { this.color = color; this.selected = selected; this.width = width; this.height = height; initPolygon(); } private void initPolygon() { poly = new Polygon(); int halfWidth = width / 2; int halfHeight = height / 2; poly.addPoint(0, halfHeight); poly.addPoint(halfWidth, 0); poly.addPoint(width, halfHeight); poly.addPoint(halfWidth, height); } public int getIconHeight() { return height; } public int getIconWidth() { return width; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(color); g.translate(x, y); if (selected) { g.fillPolygon(poly); } else { g.drawPolygon(poly); } g.translate(-x, -y); }
}
</source>
File Chooser Demo 4
<source lang="java">
/* Definitive Guide to Swing for Java 2, Second Edition By John Zukowski ISBN: 1-893115-78-X Publisher: APress
- /
import java.awt.BorderLayout; import java.awt.Color; import java.awt.ruponent; import java.awt.Container; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Image; import java.awt.Polygon; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileView; public class FilterSample {
public static void main(String args[]) { JFrame frame = new JFrame("JFileChooser Filter Popup"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); final JLabel directoryLabel = new JLabel(); contentPane.add(directoryLabel, BorderLayout.NORTH); final JLabel filenameLabel = new JLabel(); contentPane.add(filenameLabel, BorderLayout.SOUTH); final JButton button = new JButton("Open FileChooser"); ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent actionEvent) { Component parent = (Component) actionEvent.getSource(); JFileChooser fileChooser = new JFileChooser("."); fileChooser.setAccessory(new LabelAccessory(fileChooser)); FileFilter filter1 = new ExtensionFileFilter(null, new String[] { "JPG", "JPEG" }); // fileChooser.setFileFilter(filter1); fileChooser.addChoosableFileFilter(filter1); FileFilter filter2 = new ExtensionFileFilter("gif", new String[] { "gif" }); fileChooser.addChoosableFileFilter(filter2); fileChooser.setFileView(new JavaFileView()); int status = fileChooser.showOpenDialog(parent); if (status == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); directoryLabel.setText(selectedFile.getParent()); filenameLabel.setText(selectedFile.getName()); } else if (status == JFileChooser.CANCEL_OPTION) { directoryLabel.setText(" "); filenameLabel.setText(" "); } } }; button.addActionListener(actionListener); contentPane.add(button, BorderLayout.CENTER); frame.setSize(300, 200); frame.setVisible(true); }
} 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); } } }
} 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) { // Since no description, use first extension and # of extensions as // description this.description = extensions[0] + "{" + extensions.length + "}"; } else { this.description = description; } this.extensions = (String[]) extensions.clone(); // Convert array to lowercase // Don"t alter original entries 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; } // ignore case, always accept directories // character before extension must be a period 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; }
} class JavaFileView extends FileView {
Icon javaIcon = new DiamondIcon(Color.blue); Icon classIcon = new DiamondIcon(Color.green); Icon htmlIcon = new DiamondIcon(Color.red); Icon jarIcon = new DiamondIcon(Color.pink); 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")) { typeDescription = "Java Source"; } else if (filename.endsWith(".class")) { typeDescription = "Java Class File"; } else if (filename.endsWith(".jar")) { typeDescription = "Java Archive"; } else if (filename.endsWith(".html") || filename.endsWith(".htm")) { typeDescription = "Applet Loader"; } return typeDescription; } public Icon getIcon(File file) { if (file.isDirectory()) { return null; } Icon icon = null; String filename = file.getName().toLowerCase(); if (filename.endsWith(".java")) { icon = javaIcon; } else if (filename.endsWith(".class")) { icon = classIcon; } else if (filename.endsWith(".jar")) { icon = jarIcon; } else if (filename.endsWith(".html") || filename.endsWith(".htm")) { icon = htmlIcon; } return icon; }
} class DiamondIcon implements Icon {
private Color color; private boolean selected; private int width; private int height; private Polygon poly; private static final int DEFAULT_WIDTH = 10; private static final int DEFAULT_HEIGHT = 10; public DiamondIcon(Color color) { this(color, true, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected) { this(color, selected, DEFAULT_WIDTH, DEFAULT_HEIGHT); } public DiamondIcon(Color color, boolean selected, int width, int height) { this.color = color; this.selected = selected; this.width = width; this.height = height; initPolygon(); } private void initPolygon() { poly = new Polygon(); int halfWidth = width / 2; int halfHeight = height / 2; poly.addPoint(0, halfHeight); poly.addPoint(halfWidth, 0); poly.addPoint(width, halfHeight); poly.addPoint(halfWidth, height); } public int getIconHeight() { return height; } public int getIconWidth() { return width; } public void paintIcon(Component c, Graphics g, int x, int y) { g.setColor(color); g.translate(x, y); if (selected) { g.fillPolygon(poly); } else { g.drawPolygon(poly); } g.translate(-x, -y); }
}
</source>
FileChooser file filter customized filechooser
<source lang="java">
import java.awt.Container; import java.awt.Frame; 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.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.filechooser.FileFilter; public class FileChooserDemo extends JFrame implements ActionListener {
public FileChooserDemo() { setTitle("ZipTest"); setSize(300, 400); JMenuBar mbar = new JMenuBar(); JMenu m = new JMenu("File"); openItem = new JMenuItem("Open"); openItem.addActionListener(this); m.add(openItem); exitItem = new JMenuItem("Exit"); exitItem.addActionListener(this); m.add(exitItem); mbar.add(m); Container contentPane = getContentPane(); contentPane.add(mbar, "North"); } public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == openItem) { JFileChooser chooser = new JFileChooser(); chooser.setCurrentDirectory(new File(".")); chooser.setFileFilter(new FileFilter() { public boolean accept(File f) { return f.getName().toLowerCase().endsWith(".zip") || f.isDirectory(); } public String getDescription() { return "ZIP Files"; } }); int r = chooser.showOpenDialog(this); if (r == JFileChooser.APPROVE_OPTION) { String zipname = chooser.getSelectedFile().getPath(); System.out.println(zipname); } } else if (source == exitItem) System.exit(0); } public static void main(String[] args) { Frame f = new FileChooserDemo(); f.show(); } private JMenuItem openItem; private JMenuItem exitItem;
}
</source>
Files filter that filters files by their suffix (or extension)
<source lang="java">
/*
* $Id: SuffixFilenameFilter.java,v 1.1.1.1 2005/04/07 18:36:22 pocho Exp $ */
import java.io.File; import java.io.FilenameFilter; import javax.swing.filechooser.FileFilter; /**
* Files filter that filters files by their suffix (or extension). * It can be used as file filter for {@link javax.swing.JFileChooser} or * as file filter for io operations (@link java.io.File#listFiles(java.io.FilenameFilter)}. * * @version $Name: $ - $Revision: 1.1.1.1 $ - $Date: 2005/04/07 18:36:22 $ * TODO Test */
public class SuffixFilenameFilter extends FileFilter implements FilenameFilter {
/** Suffix of files */ private String suffix; /** Description of suffix (i.e. .jpg may have description JPG)*/ private String description; /** Full description of filter - (i.e. JPG (.jpg) */ private String fullDescription; /** Indicates whether to use suffix in brackets after description */ private boolean useExtensionInDescription = true; /** * Creates new instance with a given accepted suffix of file names. * * @param suffix used suffix of files (i.e. extension ".xml") */ public SuffixFilenameFilter(String suffix) { this(suffix, null); } /** * Creates new instance with a given accepted suffix of file names. * * @param suffix used suffix of files (i.e. extension ".xml") */ public SuffixFilenameFilter(String suffix, String description) { super(); setSuffix(suffix); setDescription(description); } /** * Indicates whether the name is accepted by this filter or not. * File must ending with given mask of this filter. * * @param dir File * @param name String * @return boolean */ public boolean accept(File dir, String name){ if (name.lastIndexOf(suffix) > 0) return true; else return false; } public boolean accept(File file) { if (file != null) { if (file.isDirectory() || accept(file.getParentFile(), file.getName())) return true; } return false; } /** * Returns description of this filter - if {@link #isExtensionInDescription()} * is <code>true then it creates description in following shape:
*description (suffix)
. Otherwise it only returns description. * * @see javax.swing.filechooser.FileFilter#getDescription() */ public String getDescription() { if (fullDescription == null && isExtensionInDescription()) { fullDescription = description==null ? "(" : description + " ("; fullDescription += suffix + ")"; } return fullDescription; } /** * Sets whether to use suffix in description of this filter. * * @param b */ public void setExtensionInDescription(boolean b) { useExtensionInDescription = b; fullDescription = null; } public boolean isExtensionInDescription() { return useExtensionInDescription; } public void setSuffix(String suffix) { this.suffix = suffix; fullDescription = null; } public void setDescription(String description) { this.description = description; fullDescription = null; } public String getExtension() { return suffix; } public String getSimpleDescription() { return description; }
}
</source>
Generic File Filter
<source lang="java">
import java.io.File; import javax.swing.filechooser.FileFilter; public class GenericFileFilter extends FileFilter {
private String[] fileExts; private String description; private String extension; public GenericFileFilter(String[] filesExtsIn, String description) { fileExts = filesExtsIn; this.description = description; } public boolean accept(File f) { if (f.isDirectory()) { return true; } extension = getExtension(f); if (extension != null) { for (int i = 0; i < fileExts.length; i++) { if (check(fileExts[i])) return true; } } return false; } private boolean check(String in) { return extension.equalsIgnoreCase(in); } public String getDescription() { return description; } private String getExtension(File file) { String filename = file.getName(); int length = filename.length(); int i = filename.lastIndexOf("."); if (i > 0 && i < length - 1) return filename.substring(i + 1).toLowerCase(); return null; }
}
</source>
Get Directory Choice
<source lang="java">
/*
* 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; }
}
</source>
Get File Choice
<source lang="java">
/*
* 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; }
}
</source>
Getting and Setting the Current Directory of a JFileChooser Dialog
<source lang="java">
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(); }
}
</source>
Getting and Setting the Selected File of a JFileChooser Dialog
<source lang="java">
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(); }
}
</source>
Getting the File-Type Icon of a File
<source lang="java">
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); }
}
</source>
Getting the File-Type Name of a File
<source lang="java">
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("filename.txt"); String fileTypeName = chooser.getTypeDescription(file); }
}
</source>
Getting the Large File-Type Icon of a File
<source lang="java">
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()); }
}
</source>
JDialog javax.swing.JFileChooser.createDialog(Component parent)
<source lang="java">
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); }
}
</source>
JFileChooser class in action with an accessory
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// AccessoryFileChooser.java //An example of the JFileChooser class in action with an accessory. This //accessory (see AudioAccessory.java) will play simple audio files within //the file chooser. // import java.applet.Applet; import java.applet.AudioClip; import java.awt.BorderLayout; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.net.URL; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class AccessoryFileChooser extends JFrame {
JFileChooser chooser = null; JLabel statusbar; public AccessoryFileChooser() { super("Accessory Test Frame"); setSize(350, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton accButton = new JButton("Accessory"); statusbar = new JLabel("Output of your selection will go here"); chooser = new JFileChooser(); AudioAccessory aa = new AudioAccessory(); chooser.setAccessory(aa); chooser.addPropertyChangeListener(aa); // to receive selection changes chooser.addActionListener(aa); // to receive approve/cancel button // events accButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { int option = chooser.showOpenDialog(AccessoryFileChooser.this); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You chose " + ((chooser.getSelectedFile() != null) ? chooser .getSelectedFile().getName() : "nothing")); } else { statusbar.setText("You canceled."); } } }); c.add(accButton); c.add(statusbar); } public static void main(String args[]) { AccessoryFileChooser afc = new AccessoryFileChooser(); afc.setVisible(true); }
} //AudioAccessory.java //An accessory for JFileChooser that lets you play music clips. Only the //simple .au, .aiff and .wav formats available through the Applet sound //classes can be played. // class AudioAccessory extends JPanel implements PropertyChangeListener,
ActionListener { AudioClip currentClip; String currentName = ""; JLabel fileLabel; JButton playButton, stopButton; public AudioAccessory() { // Set up the accessory. The file chooser will give us a reasonable // size. setLayout(new BorderLayout()); add(fileLabel = new JLabel("Clip Name"), BorderLayout.NORTH); JPanel p = new JPanel(); playButton = new JButton("Play"); stopButton = new JButton("Stop"); playButton.setEnabled(false); stopButton.setEnabled(false); p.add(playButton); p.add(stopButton); add(p, BorderLayout.CENTER); playButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentClip != null) { currentClip.stop(); currentClip.play(); } } }); stopButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (currentClip != null) { currentClip.stop(); } } }); } public void propertyChange(PropertyChangeEvent e) { String pname = e.getPropertyName(); if (JFileChooser.SELECTED_FILE_CHANGED_PROPERTY.equals(pname)) { // Ok, the user selected a file in the chooser File f = (File) e.getNewValue(); // Make reasonably sure it"s an audio file if ((f != null) && (f.getName().toLowerCase().endsWith(".au") || f.getName().toLowerCase().endsWith(".wav") || f.getName().toLowerCase().endsWith(".aif") || f .getName().toLowerCase().endsWith(".aiff"))) { setCurrentClip(f); } else { setCurrentClip(null); } } } public void setCurrentClip(File f) { if (currentClip != null) { currentClip.stop(); } // Make sure we have a real file, otherwise, disable the buttons if ((f == null) || (f.getName() == null)) { fileLabel.setText("no audio selected"); playButton.setEnabled(false); stopButton.setEnabled(false); return; } // Ok, seems the audio file is real, so load it and enable the buttons String name = f.getName(); if (name.equals(currentName)) { // Same clip they just loaded...make sure the player is enabled fileLabel.setText(name); playButton.setEnabled(true); stopButton.setEnabled(true); return; } currentName = name; try { URL u = new URL("file:///" + f.getAbsolutePath()); currentClip = Applet.newAudioClip(u); } catch (Exception e) { e.printStackTrace(); currentClip = null; fileLabel.setText("Error loading clip."); } fileLabel.setText(name); playButton.setEnabled(true); stopButton.setEnabled(true); } public void actionPerformed(ActionEvent ae) { // Be a little cavalier here...we"re assuming the dialog was just // approved or cancelled so we should stop any playing clip if (currentClip != null) { currentClip.stop(); } }
}
</source>
JFileChooser is a standard dialog for selecting a file from the file system.
<source lang="java">
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); } }
}
</source>
Listening for Approve and Cancel Events in a JFileChooser Dialog
<source lang="java">
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); }
}
</source>
Listening for Changes to the Selected File in a JFileChooser Dialog
<source lang="java">
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); }
}
</source>
Localize a JFileChooser
<source lang="java">
[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")); }
}
</source>
see what it takes to make one of these filters work
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// MyFilterChooser.java //Just a simple example to see what it takes to make one of these filters work. // import java.awt.Container; 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.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.filechooser.FileFilter; public class MyFilterChooser extends JFrame {
public MyFilterChooser() { super("Filter Test Frame"); setSize(350, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); final JLabel statusbar = new JLabel( "Output of your selection will go here"); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String[] pics = new String[] { "gif", "jpg", "tif" }; String[] audios = new String[] { "au", "aiff", "wav" }; JFileChooser chooser = new JFileChooser(); chooser.addChoosableFileFilter(new SimpleFileFilter(pics, "Images (*.gif, *.jpg, *.tif)")); chooser.addChoosableFileFilter(new SimpleFileFilter(".MOV")); chooser.addChoosableFileFilter(new SimpleFileFilter(audios, "Sounds (*.aiff, *.au, *.wav)")); int option = chooser.showOpenDialog(MyFilterChooser.this); if (option == JFileChooser.APPROVE_OPTION) { if (chooser.getSelectedFile() != null) statusbar.setText("You chose " + chooser.getSelectedFile().getName()); } else { statusbar.setText("You canceled."); } } }); c.add(openButton); c.add(statusbar); setVisible(true); } public static void main(String args[]) { MyFilterChooser mfc = new MyFilterChooser(); }
} //SimpleFileFilter.java //A straightforward extension-based example of a file filter. This should be //replaced by a "first class" Swing class in a later release of Swing. // class SimpleFileFilter extends FileFilter {
String[] extensions; String description; public SimpleFileFilter(String ext) { this(new String[] { ext }, null); } public SimpleFileFilter(String[] exts, String descr) { // Clone and lowercase the extensions extensions = new String[exts.length]; for (int i = exts.length - 1; i >= 0; i--) { extensions[i] = exts[i].toLowerCase(); } // Make sure we have a valid (if simplistic) description description = (descr == null ? exts[0] + " files" : descr); } public boolean accept(File f) { // We always allow directories, regardless of their extension if (f.isDirectory()) { return true; } // Ok, it"s a regular file, so check the extension String name = f.getName().toLowerCase(); for (int i = extensions.length - 1; i >= 0; i--) { if (name.endsWith(extensions[i])) { return true; } } return false; } public String getDescription() { return description; }
}
</source>
Select a directory with a JFileChooser
<source lang="java">
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 "); } }
}
</source>
Showing Hidden Files in a JFileChooser Dialog
<source lang="java">
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); }
}
</source>
show thumbnails of graphic files
<source lang="java">
/* Java Swing, 2nd Edition By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole ISBN: 0-596-00408-7 Publisher: O"Reilly
- /
// MyViewChooser.java //An example that uses custom file views to show thumbnails of graphic files //rather than the regular file icon. (see ThumbnailFileView.java) // import java.awt.ruponent; import java.awt.Container; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.filechooser.FileView; import javax.swing.plaf.metal.MetalIconFactory; public class MyViewChooser extends JFrame {
JFrame parent; public MyViewChooser() { super("File View Test Frame"); setSize(350, 200); setDefaultCloseOperation(EXIT_ON_CLOSE); parent = this; Container c = getContentPane(); c.setLayout(new FlowLayout()); JButton openButton = new JButton("Open"); final JLabel statusbar = new JLabel( "Output of your selection will go here"); openButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { JFileChooser chooser = new JFileChooser(); // Ok, set up our own file view for the chooser chooser.setFileView(new ThumbNailFileView(MyViewChooser.this)); int option = chooser.showOpenDialog(parent); if (option == JFileChooser.APPROVE_OPTION) { statusbar.setText("You chose " + chooser.getSelectedFile().getName()); } else { statusbar.setText("You cancelled."); } } }); c.add(openButton); c.add(statusbar); } public static void main(String args[]) { System.setProperty("swing.defaultlaf", "javax.swing.plaf.metal.MetalLookAndFeel"); MyViewChooser vc = new MyViewChooser(); vc.setVisible(true); }
} //ThumbNailFileView.java //A simple implementation of the FileView class that provides a 16x16 image of //each GIF or JPG file for its icon. This could be SLOW for large images, as we //simply load the real image and then scale it. // class ThumbNailFileView extends FileView {
private Icon fileIcon = MetalIconFactory.getTreeLeafIcon(); private Icon folderIcon = MetalIconFactory.getTreeFolderIcon(); private Component observer; public ThumbNailFileView(Component c) { // We need a component around to create our icon"s image observer = c; } public String getDescription(File f) { // We won"t store individual descriptions, so just return the // type description. return getTypeDescription(f); } public Icon getIcon(File f) { // Is it a folder? if (f.isDirectory()) { return folderIcon; } // Ok, it"s a file, so return a custom icon if it"s an image file String name = f.getName().toLowerCase(); if (name.endsWith(".jpg") || name.endsWith(".gif")) { return new Icon16(f.getAbsolutePath()); } // Return the generic file icon if it"s not return fileIcon; } public String getName(File f) { String name = f.getName(); return name.equals("") ? f.getPath() : name; } public String getTypeDescription(File f) { String name = f.getName().toLowerCase(); if (f.isDirectory()) { return "Folder"; } if (name.endsWith(".jpg")) { return "JPEG Image"; } if (name.endsWith(".gif")) { return "GIF Image"; } return "Generic File"; } public Boolean isTraversable(File f) { // We"ll mark all directories as traversable return f.isDirectory() ? Boolean.TRUE : Boolean.FALSE; } public class Icon16 extends ImageIcon { public Icon16(String f) { super(f); Image i = observer.createImage(16, 16); i.getGraphics().drawImage(getImage(), 0, 0, 16, 16, observer); setImage(i); } public int getIconHeight() { return 16; } public int getIconWidth() { return 16; } public void paintIcon(Component c, Graphics g, int x, int y) { g.drawImage(getImage(), x, y, c); } }
}
</source>
String javax.swing.JFileChooser.APPROVE_SELECTION
<source lang="java">
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); }
}
</source>
Suffix FileFilter
<source lang="java">
/*
* Project: Gulden Utilies * Class: de.gulden.util.swing.SuffixFileFilter * Version: snapshot-beautyj-1.1 * * Date: 2004-09-29 * * This is a snapshot version of the Gulden Utilities, * it is not released as a seperate version. * * Note: Contains auto-generated Javadoc comments created by BeautyJ. * * This is licensed under the GNU Lesser General Public License (LGPL) * and comes with NO WARRANTY. * * Author: Jens Gulden * Email: amoda@jensgulden.de */
import java.io.File; import java.util.*; import javax.swing.filechooser.FileFilter; /**
* Class SuffixFileFilter. * * @author Jens Gulden * @version snapshot-beautyj-1.1 */
public class SuffixFileFilter extends FileFilter {
// ------------------------------------------------------------------------ // --- fields --- // ------------------------------------------------------------------------ /** * The suffix. */ protected String suffix; /** * The description. */ protected String description;
// ------------------------------------------------------------------------ // --- constructors --- // ------------------------------------------------------------------------ /** * Creates a new instance of SuffixFileFilter. */ public SuffixFileFilter() { super(); } /** * Creates a new instance of SuffixFileFilter. */ public SuffixFileFilter(String suffix, String description) { this(); this.suffix=suffix; this.description=description; }
// ------------------------------------------------------------------------ // --- methods --- // ------------------------------------------------------------------------ /** * Returns the suffix. */ public String getSuffix() { return suffix; } /** * Sets the suffix. */ public void setSuffix(String _suffix) { suffix = _suffix; } /** * Returns the description. */ public String getDescription() { return "*."+getSuffix()+" - "+description; } /** * Sets the description. */ public void setDescription(String _description) { description = _description; } public boolean accept(File file) { if (file.isDirectory()) { // must accept to allow user choosing and navigating in directories return true; } String suffix=getSuffix(); if ((suffix==null)||suffix.equals("")||suffix.equals("*")) { return true; } else { String f=file.getName(); return f.endsWith("."+suffix); } }
} // end SuffixFileFilter
</source>
Swing File Chooser Demo
<source lang="java">
/* From http://java.sun.ru/docs/books/tutorial/index.html */ /*
* Copyright (c) 2006 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: * * -Redistribution of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * -Redistribution in binary form must reproduce 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 MIDROSYSTEMS, INC. ("SUN") * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS 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 THIS SOFTWARE, * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. * * You acknowledge that this software is not designed, licensed or intended * for use in the design, construction, operation or maintenance of any * nuclear facility. */
import java.awt.BorderLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; /*
* SwingFileChooserDemo.java is a 1.4 application that uses these files: * images/Open16.gif images/Save16.gif */
public class SwingFileChooserDemo extends JPanel implements ActionListener {
static private final String newline = "\n"; JButton openButton, saveButton; JTextArea log; JFileChooser fc; public SwingFileChooserDemo() { super(new BorderLayout()); //Create the log first, because the action listeners //need to refer to it. log = new JTextArea(5, 20); log.setMargin(new Insets(5, 5, 5, 5)); log.setEditable(false); JScrollPane logScrollPane = new JScrollPane(log); //Create a file chooser fc = new JFileChooser(); //Uncomment one of the following lines to try a different //file selection mode. The first allows just directories //to be selected (and, at least in the Java look and feel, //shown). The second allows both files and directories //to be selected. If you leave these lines commented out, //then the default mode (FILES_ONLY) will be used. // //fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES); //Create the open button. We use the image from the JLF //Graphics Repository (but we extracted it from the jar). openButton = new JButton("Open a File...", createImageIcon("images/Open16.gif")); openButton.addActionListener(this); //Create the save button. We use the image from the JLF //Graphics Repository (but we extracted it from the jar). saveButton = new JButton("Save a File...", createImageIcon("images/Save16.gif")); saveButton.addActionListener(this); //For layout purposes, put the buttons in a separate panel JPanel buttonPanel = new JPanel(); //use FlowLayout buttonPanel.add(openButton); buttonPanel.add(saveButton); //Add the buttons and the log to this panel. add(buttonPanel, BorderLayout.PAGE_START); add(logScrollPane, BorderLayout.CENTER); } public void actionPerformed(ActionEvent e) { //Handle open button action. if (e.getSource() == openButton) { int returnVal = fc.showOpenDialog(SwingFileChooserDemo.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); } log.setCaretPosition(log.getDocument().getLength()); //Handle save button action. } else if (e.getSource() == saveButton) { int returnVal = fc.showSaveDialog(SwingFileChooserDemo.this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); //This is where a real application would save the file. log.append("Saving: " + file.getName() + "." + newline); } else { log.append("Save command cancelled by user." + newline); } log.setCaretPosition(log.getDocument().getLength()); } } /** Returns an ImageIcon, or null if the path was invalid. */ protected static ImageIcon createImageIcon(String path) { java.net.URL imgURL = SwingFileChooserDemo.class.getResource(path); if (imgURL != null) { return new ImageIcon(imgURL); } else { System.err.println("Couldn"t find file: " + path); return null; } } /** * Create the GUI and show it. For thread safety, this method should be * invoked from the event-dispatching thread. */ private static void createAndShowGUI() { //Make sure we have nice window decorations. JFrame.setDefaultLookAndFeelDecorated(true); JDialog.setDefaultLookAndFeelDecorated(true); //Create and set up the window. JFrame frame = new JFrame("SwingFileChooserDemo"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Create and set up the content pane. JComponent newContentPane = new SwingFileChooserDemo(); newContentPane.setOpaque(true); //content panes must be opaque frame.setContentPane(newContentPane); //Display the window. frame.pack(); frame.setVisible(true); } public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //creating and showing this application"s GUI. javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); }
}
</source>
Validate a filename from a JFileChooser
<source lang="java">
import javax.swing.JFileChooser; import javax.swing.JOptionPane; public class Main {
public static void main(String s[]) { JFileChooser chooser = new JFileChooser(); int rc = chooser.showOpenDialog(null); while (rc == JFileChooser.APPROVE_OPTION && !chooser.getSelectedFile().getName().endsWith(".java")) { JOptionPane.showMessageDialog(null, "The file " + chooser.getSelectedFile() + " is not java source file.", "Open Error", JOptionPane.ERROR_MESSAGE); rc = chooser.showOpenDialog(null); } }
}
</source>
void javax.swing.JFileChooser.addActionListener(ActionListener l)
<source lang="java">
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); }
}
</source>
void javax.swing.JFileChooser.setDialogType(int dialogType)
<source lang="java">
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); }
}
</source>