jdk/src/share/demo/jfc/FileChooserDemo/FileChooserDemo.java
changeset 8968 46991a517c09
parent 5506 202f599c92aa
child 10292 ed7db6a12c2a
equal deleted inserted replaced
8967:57934762bad8 8968:46991a517c09
     1 /*
     1 /*
     2  * Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
     2  * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
     3  *
     3  *
     4  * Redistribution and use in source and binary forms, with or without
     4  * Redistribution and use in source and binary forms, with or without
     5  * modification, are permitted provided that the following conditions
     5  * modification, are permitted provided that the following conditions
     6  * are met:
     6  * are met:
     7  *
     7  *
    27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    30  */
    30  */
    31 
    31 
    32 /*
    32 
    33  */
    33 import java.lang.reflect.InvocationTargetException;
    34 
    34 import java.util.logging.Level;
    35 import javax.swing.*;
    35 import java.util.logging.Logger;
    36 import javax.swing.filechooser.*;
    36 import javax.swing.UIManager.LookAndFeelInfo;
       
    37 import java.awt.BorderLayout;
       
    38 import java.awt.CardLayout;
       
    39 import java.awt.Component;
       
    40 import java.awt.Dimension;
       
    41 import java.awt.Graphics;
       
    42 import java.awt.Image;
       
    43 import java.awt.Insets;
       
    44 import java.awt.event.ActionEvent;
       
    45 import java.awt.event.ActionListener;
       
    46 import java.beans.PropertyChangeEvent;
       
    47 import java.beans.PropertyChangeListener;
       
    48 import java.util.List;
       
    49 import javax.swing.BorderFactory;
       
    50 import javax.swing.Box;
       
    51 import javax.swing.BoxLayout;
       
    52 import javax.swing.ButtonGroup;
       
    53 import javax.swing.DefaultComboBoxModel;
       
    54 import javax.swing.ImageIcon;
       
    55 import javax.swing.JButton;
       
    56 import javax.swing.JCheckBox;
       
    57 import javax.swing.JComboBox;
       
    58 import javax.swing.JComponent;
       
    59 import javax.swing.JDialog;
       
    60 import javax.swing.JFileChooser;
       
    61 import javax.swing.JFrame;
       
    62 import javax.swing.JLabel;
       
    63 import javax.swing.JOptionPane;
       
    64 import javax.swing.JPanel;
       
    65 import javax.swing.JRadioButton;
       
    66 import javax.swing.JTextField;
       
    67 import javax.swing.JToggleButton;
       
    68 import javax.swing.LookAndFeel;
       
    69 import javax.swing.SwingUtilities;
       
    70 import javax.swing.UIManager;
       
    71 import javax.swing.UnsupportedLookAndFeelException;
       
    72 import javax.swing.WindowConstants;
       
    73 import javax.swing.filechooser.FileFilter;
       
    74 import javax.swing.filechooser.FileNameExtensionFilter;
       
    75 import javax.swing.filechooser.FileSystemView;
       
    76 import java.util.ArrayList;
    37 import javax.swing.plaf.FileChooserUI;
    77 import javax.swing.plaf.FileChooserUI;
    38 import javax.swing.plaf.basic.BasicFileChooserUI;
    78 import javax.swing.plaf.basic.BasicFileChooserUI;
    39 
       
    40 import java.awt.*;
       
    41 import java.io.File;
    79 import java.io.File;
    42 import java.awt.event.*;
       
    43 import java.beans.*;
       
    44 import java.util.Vector;
       
    45 
       
    46 import static javax.swing.JFileChooser.*;
    80 import static javax.swing.JFileChooser.*;
       
    81 
    47 
    82 
    48 /**
    83 /**
    49  *
    84  *
    50  * A demo which makes extensive use of the file chooser.
    85  * A demo which makes extensive use of the file chooser.
    51  *
    86  *
    52  * @author Jeff Dinkins
    87  * @author Jeff Dinkins
    53  */
    88  */
       
    89 @SuppressWarnings("serial")
    54 public class FileChooserDemo extends JPanel implements ActionListener {
    90 public class FileChooserDemo extends JPanel implements ActionListener {
       
    91 
       
    92     public static final String NIMBUS_LAF_NAME = "Nimbus";
    55     private static JFrame frame;
    93     private static JFrame frame;
    56 
    94     private final List<SupportedLaF> supportedLaFs =
    57     private final Vector<SupportedLaF> supportedLaFs = new Vector();
    95             new ArrayList<SupportedLaF>();
       
    96     private static SupportedLaF nimbusLaF;
       
    97 
    58 
    98 
    59     private static class SupportedLaF {
    99     private static class SupportedLaF {
       
   100 
    60         private final String name;
   101         private final String name;
    61         private final LookAndFeel laf;
   102         private final LookAndFeel laf;
    62 
   103 
    63         SupportedLaF(String name, LookAndFeel laf) {
   104         SupportedLaF(String name, LookAndFeel laf) {
    64             this.name = name;
   105             this.name = name;
    65             this.laf = laf;
   106             this.laf = laf;
    66         }
   107         }
    67 
   108 
       
   109         @Override
    68         public String toString() {
   110         public String toString() {
    69             return name;
   111             return name;
    70         }
   112         }
    71     }
   113     }
    72 
       
    73 
       
    74     private JButton showButton;
   114     private JButton showButton;
    75 
       
    76     private JCheckBox showAllFilesFilterCheckBox;
   115     private JCheckBox showAllFilesFilterCheckBox;
    77     private JCheckBox showImageFilesFilterCheckBox;
   116     private JCheckBox showImageFilesFilterCheckBox;
    78     private JCheckBox showFullDescriptionCheckBox;
   117     private JCheckBox showFullDescriptionCheckBox;
    79 
       
    80     private JCheckBox useFileViewCheckBox;
   118     private JCheckBox useFileViewCheckBox;
    81     private JCheckBox useFileSystemViewCheckBox;
   119     private JCheckBox useFileSystemViewCheckBox;
    82     private JCheckBox accessoryCheckBox;
   120     private JCheckBox accessoryCheckBox;
    83     private JCheckBox setHiddenCheckBox;
   121     private JCheckBox setHiddenCheckBox;
    84     private JCheckBox useEmbedInWizardCheckBox;
   122     private JCheckBox useEmbedInWizardCheckBox;
    85     private JCheckBox useControlsCheckBox;
   123     private JCheckBox useControlsCheckBox;
    86     private JCheckBox enableDragCheckBox;
   124     private JCheckBox enableDragCheckBox;
    87 
       
    88     private JRadioButton singleSelectionRadioButton;
   125     private JRadioButton singleSelectionRadioButton;
    89     private JRadioButton multiSelectionRadioButton;
   126     private JRadioButton multiSelectionRadioButton;
    90 
       
    91     private JRadioButton openRadioButton;
   127     private JRadioButton openRadioButton;
    92     private JRadioButton saveRadioButton;
   128     private JRadioButton saveRadioButton;
    93     private JRadioButton customButton;
   129     private JRadioButton customButton;
    94 
       
    95     private JComboBox lafComboBox;
   130     private JComboBox lafComboBox;
    96 
       
    97     private JRadioButton justFilesRadioButton;
   131     private JRadioButton justFilesRadioButton;
    98     private JRadioButton justDirectoriesRadioButton;
   132     private JRadioButton justDirectoriesRadioButton;
    99     private JRadioButton bothFilesAndDirectoriesRadioButton;
   133     private JRadioButton bothFilesAndDirectoriesRadioButton;
   100 
       
   101     private JTextField customField;
   134     private JTextField customField;
   102 
       
   103     private final ExampleFileView fileView;
   135     private final ExampleFileView fileView;
   104 
       
   105     private final ExampleFileSystemView fileSystemView;
   136     private final ExampleFileSystemView fileSystemView;
   106 
   137     private final static Dimension hpad10 = new Dimension(10, 1);
   107     private final static Dimension hpad10 = new Dimension(10,1);
   138     private final static Dimension vpad20 = new Dimension(1, 20);
   108     private final static Dimension vpad20 = new Dimension(1,20);
       
   109     private final static Dimension vpad7 = new Dimension(1, 7);
   139     private final static Dimension vpad7 = new Dimension(1, 7);
   110     private final static Dimension vpad4 = new Dimension(1, 4);
   140     private final static Dimension vpad4 = new Dimension(1, 4);
   111     private final static Insets insets = new Insets(5, 10, 0, 10);
   141     private final static Insets insets = new Insets(5, 10, 0, 10);
   112 
       
   113     private final FilePreviewer previewer;
   142     private final FilePreviewer previewer;
   114     private final JFileChooser chooser;
   143     private final JFileChooser chooser;
   115 
   144 
       
   145     @SuppressWarnings("LeakingThisInConstructor")
   116     public FileChooserDemo() {
   146     public FileChooserDemo() {
   117         UIManager.LookAndFeelInfo[] installedLafs = UIManager.getInstalledLookAndFeels();
   147         UIManager.LookAndFeelInfo[] installedLafs = UIManager.
       
   148                 getInstalledLookAndFeels();
   118         for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
   149         for (UIManager.LookAndFeelInfo lafInfo : installedLafs) {
   119             try {
   150             try {
   120                 Class lnfClass = Class.forName(lafInfo.getClassName());
   151                 Class<?> lnfClass = Class.forName(lafInfo.getClassName());
   121                 LookAndFeel laf = (LookAndFeel)(lnfClass.newInstance());
   152                 LookAndFeel laf = (LookAndFeel) (lnfClass.newInstance());
   122                 if (laf.isSupportedLookAndFeel()) {
   153                 if (laf.isSupportedLookAndFeel()) {
   123                     String name = lafInfo.getName();
   154                     String name = lafInfo.getName();
   124                     supportedLaFs.add(new SupportedLaF(name, laf));
   155                     SupportedLaF supportedLaF = new SupportedLaF(name, laf);
   125                 }
   156                     supportedLaFs.add(supportedLaF);
   126             } catch (Exception e) { // If ANYTHING weird happens, don't add it
   157                     if (NIMBUS_LAF_NAME.equals(name)) {
       
   158                         nimbusLaF = supportedLaF;
       
   159                     }
       
   160                 }
       
   161             } catch (Exception ignored) {
       
   162                 // If ANYTHING weird happens, don't add this L&F
   127             }
   163             }
   128         }
   164         }
   129 
   165 
   130         setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
   166         setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
   131 
   167 
   132         chooser = new JFileChooser();
   168         chooser = new JFileChooser();
   133         previewer = new FilePreviewer(chooser);
   169         previewer = new FilePreviewer(chooser);
   134 
   170 
   135         // Create Custom FileView
   171         // Create Custom FileView
   136         fileView = new ExampleFileView();
   172         fileView = new ExampleFileView();
   137         fileView.putIcon("jpg", new ImageIcon(getClass().getResource("/resources/images/jpgIcon.jpg")));
   173         fileView.putIcon("jpg", new ImageIcon(getClass().getResource(
   138         fileView.putIcon("gif", new ImageIcon(getClass().getResource("/resources/images/gifIcon.gif")));
   174                 "/resources/images/jpgIcon.jpg")));
       
   175         fileView.putIcon("gif", new ImageIcon(getClass().getResource(
       
   176                 "/resources/images/gifIcon.gif")));
   139 
   177 
   140         // Create Custom FileSystemView
   178         // Create Custom FileSystemView
   141         fileSystemView = new ExampleFileSystemView();
   179         fileSystemView = new ExampleFileSystemView();
   142 
   180 
   143         // create a radio listener to listen to option changes
   181         // create a radio listener to listen to option changes
   153 
   191 
   154         customButton = new JRadioButton("Custom");
   192         customButton = new JRadioButton("Custom");
   155         customButton.addActionListener(optionListener);
   193         customButton.addActionListener(optionListener);
   156 
   194 
   157         customField = new JTextField(8) {
   195         customField = new JTextField(8) {
       
   196 
       
   197             @Override
   158             public Dimension getMaximumSize() {
   198             public Dimension getMaximumSize() {
   159                 return new Dimension(getPreferredSize().width, getPreferredSize().height);
   199                 return new Dimension(getPreferredSize().width,
       
   200                         getPreferredSize().height);
   160             }
   201             }
   161         };
   202         };
   162         customField.setText("Doit");
   203         customField.setText("Doit");
   163         customField.setAlignmentY(JComponent.TOP_ALIGNMENT);
   204         customField.setAlignmentY(JComponent.TOP_ALIGNMENT);
   164         customField.setEnabled(false);
   205         customField.setEnabled(false);
   218 
   259 
   219         justDirectoriesRadioButton = new JRadioButton("Just Select Directories");
   260         justDirectoriesRadioButton = new JRadioButton("Just Select Directories");
   220         group3.add(justDirectoriesRadioButton);
   261         group3.add(justDirectoriesRadioButton);
   221         justDirectoriesRadioButton.addActionListener(optionListener);
   262         justDirectoriesRadioButton.addActionListener(optionListener);
   222 
   263 
   223         bothFilesAndDirectoriesRadioButton = new JRadioButton("Select Files or Directories");
   264         bothFilesAndDirectoriesRadioButton = new JRadioButton(
       
   265                 "Select Files or Directories");
   224         group3.add(bothFilesAndDirectoriesRadioButton);
   266         group3.add(bothFilesAndDirectoriesRadioButton);
   225         bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);
   267         bothFilesAndDirectoriesRadioButton.addActionListener(optionListener);
   226 
   268 
   227         singleSelectionRadioButton = new JRadioButton("Single Selection", true);
   269         singleSelectionRadioButton = new JRadioButton("Single Selection", true);
   228         singleSelectionRadioButton.addActionListener(optionListener);
   270         singleSelectionRadioButton.addActionListener(optionListener);
   239         showButton = new JButton("Show FileChooser");
   281         showButton = new JButton("Show FileChooser");
   240         showButton.addActionListener(this);
   282         showButton.addActionListener(this);
   241         showButton.setMnemonic('s');
   283         showButton.setMnemonic('s');
   242 
   284 
   243         // Create laf combo box
   285         // Create laf combo box
   244         lafComboBox = new JComboBox(supportedLaFs);
   286         lafComboBox = new JComboBox(supportedLaFs.toArray());
       
   287         lafComboBox.setSelectedItem(nimbusLaF);
   245         lafComboBox.setEditable(false);
   288         lafComboBox.setEditable(false);
   246         lafComboBox.addActionListener(optionListener);
   289         lafComboBox.addActionListener(optionListener);
   247 
   290 
   248         // ********************************************************
   291         // ********************************************************
   249         // ******************** Dialog Type ***********************
   292         // ******************** Dialog Type ***********************
   315 
   358 
   316         // ********************************************************
   359         // ********************************************************
   317         // ************* File & Directory Options *****************
   360         // ************* File & Directory Options *****************
   318         // ********************************************************
   361         // ********************************************************
   319         JPanel control4 = new InsetPanel(insets);
   362         JPanel control4 = new InsetPanel(insets);
   320         control4.setBorder(BorderFactory.createTitledBorder("File and Directory Options"));
   363         control4.setBorder(BorderFactory.createTitledBorder(
       
   364                 "File and Directory Options"));
   321         control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
   365         control4.setLayout(new BoxLayout(control4, BoxLayout.Y_AXIS));
   322         control4.add(Box.createRigidArea(vpad20));
   366         control4.add(Box.createRigidArea(vpad20));
   323         control4.add(justFilesRadioButton);
   367         control4.add(justFilesRadioButton);
   324         control4.add(Box.createRigidArea(vpad7));
   368         control4.add(Box.createRigidArea(vpad7));
   325         control4.add(justDirectoriesRadioButton);
   369         control4.add(justDirectoriesRadioButton);
   377             chooser.setSelectedFile(null);
   421             chooser.setSelectedFile(null);
   378         }
   422         }
   379         // clear the preview from the previous display of the chooser
   423         // clear the preview from the previous display of the chooser
   380         JComponent accessory = chooser.getAccessory();
   424         JComponent accessory = chooser.getAccessory();
   381         if (accessory != null) {
   425         if (accessory != null) {
   382             ((FilePreviewer)accessory).loadImage(null);
   426             ((FilePreviewer) accessory).loadImage(null);
   383         }
   427         }
   384 
   428 
   385         if (useEmbedInWizardCheckBox.isSelected()) {
   429         if (useEmbedInWizardCheckBox.isSelected()) {
   386             WizardDialog wizard = new WizardDialog(frame, true);
   430             WizardDialog wizard = new WizardDialog(frame, true);
   387             wizard.setVisible(true);
   431             wizard.setVisible(true);
   391 
   435 
   392         int retval = chooser.showDialog(frame, null);
   436         int retval = chooser.showDialog(frame, null);
   393         if (retval == APPROVE_OPTION) {
   437         if (retval == APPROVE_OPTION) {
   394             JOptionPane.showMessageDialog(frame, getResultString());
   438             JOptionPane.showMessageDialog(frame, getResultString());
   395         } else if (retval == CANCEL_OPTION) {
   439         } else if (retval == CANCEL_OPTION) {
   396             JOptionPane.showMessageDialog(frame, "User cancelled operation. No file was chosen.");
   440             JOptionPane.showMessageDialog(frame,
       
   441                     "User cancelled operation. No file was chosen.");
   397         } else if (retval == ERROR_OPTION) {
   442         } else if (retval == ERROR_OPTION) {
   398             JOptionPane.showMessageDialog(frame, "An error occured. No file was chosen.");
   443             JOptionPane.showMessageDialog(frame,
       
   444                     "An error occured. No file was chosen.");
   399         } else {
   445         } else {
   400             JOptionPane.showMessageDialog(frame, "Unknown operation occured.");
   446             JOptionPane.showMessageDialog(frame, "Unknown operation occured.");
   401         }
   447         }
   402     }
   448     }
   403 
   449 
   404     private void resetFileFilters(boolean enableFilters,
   450     private void resetFileFilters(boolean enableFilters,
   405                                   boolean showExtensionInDescription) {
   451             boolean showExtensionInDescription) {
   406         chooser.resetChoosableFileFilters();
   452         chooser.resetChoosableFileFilters();
   407         if (enableFilters) {
   453         if (enableFilters) {
   408             FileFilter jpgFilter = createFileFilter("JPEG Compressed Image Files",
   454             FileFilter jpgFilter = createFileFilter(
   409                                          showExtensionInDescription, "jpg");
   455                     "JPEG Compressed Image Files",
       
   456                     showExtensionInDescription, "jpg");
   410             FileFilter gifFilter = createFileFilter("GIF Image Files",
   457             FileFilter gifFilter = createFileFilter("GIF Image Files",
   411                                          showExtensionInDescription, "gif");
   458                     showExtensionInDescription, "gif");
   412             FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
   459             FileFilter bothFilter = createFileFilter("JPEG and GIF Image Files",
   413                                           showExtensionInDescription, "jpg",
   460                     showExtensionInDescription, "jpg",
   414                                           "gif");
   461                     "gif");
   415             chooser.addChoosableFileFilter(bothFilter);
   462             chooser.addChoosableFileFilter(bothFilter);
   416             chooser.addChoosableFileFilter(jpgFilter);
   463             chooser.addChoosableFileFilter(jpgFilter);
   417             chooser.addChoosableFileFilter(gifFilter);
   464             chooser.addChoosableFileFilter(gifFilter);
   418         }
   465         }
   419     }
   466     }
   420 
   467 
   421     private FileFilter createFileFilter(String description,
   468     private FileFilter createFileFilter(String description,
   422             boolean showExtensionInDescription, String...extensions) {
   469             boolean showExtensionInDescription, String... extensions) {
   423         if (showExtensionInDescription) {
   470         if (showExtensionInDescription) {
   424             description = createFileNameFilterDescriptionFromExtensions(
   471             description = createFileNameFilterDescriptionFromExtensions(
   425                     description, extensions);
   472                     description, extensions);
   426         }
   473         }
   427         return new FileNameExtensionFilter(description, extensions);
   474         return new FileNameExtensionFilter(description, extensions);
   428     }
   475     }
   429 
   476 
   430     private String createFileNameFilterDescriptionFromExtensions(
   477     private String createFileNameFilterDescriptionFromExtensions(
   431             String description, String[] extensions) {
   478             String description, String[] extensions) {
   432         String fullDescription = (description == null) ?
   479         String fullDescription = (description == null) ? "(" : description
   433                 "(" : description + " (";
   480                 + " (";
   434         // build the description from the extension list
   481         // build the description from the extension list
   435         fullDescription += "." + extensions[0];
   482         fullDescription += "." + extensions[0];
   436         for (int i = 1; i < extensions.length; i++) {
   483         for (int i = 1; i < extensions.length; i++) {
   437             fullDescription += ", .";
   484             fullDescription += ", .";
   438             fullDescription += extensions[i];
   485             fullDescription += extensions[i];
   439         }
   486         }
   440         fullDescription += ")";
   487         fullDescription += ")";
   441         return fullDescription;
   488         return fullDescription;
   442     }
   489     }
   443 
   490 
       
   491 
   444     private class WizardDialog extends JDialog implements ActionListener {
   492     private class WizardDialog extends JDialog implements ActionListener {
       
   493 
   445         CardLayout cardLayout;
   494         CardLayout cardLayout;
   446         JPanel cardPanel;
   495         JPanel cardPanel;
   447         JLabel messageLabel;
   496         JLabel messageLabel;
   448         JButton backButton, nextButton, closeButton;
   497         JButton backButton, nextButton, closeButton;
   449 
   498 
       
   499         @SuppressWarnings("LeakingThisInConstructor")
   450         WizardDialog(JFrame frame, boolean modal) {
   500         WizardDialog(JFrame frame, boolean modal) {
   451             super(frame, "Embedded JFileChooser Demo", modal);
   501             super(frame, "Embedded JFileChooser Demo", modal);
   452 
   502 
   453             cardLayout = new CardLayout();
   503             cardLayout = new CardLayout();
   454             cardPanel = new JPanel(cardLayout);
   504             cardPanel = new JPanel(cardLayout);
   492                 FileChooserUI ui = chooser.getUI();
   542                 FileChooserUI ui = chooser.getUI();
   493                 if (ui instanceof BasicFileChooserUI) {
   543                 if (ui instanceof BasicFileChooserUI) {
   494                     // Workaround for bug 4528663. This is necessary to
   544                     // Workaround for bug 4528663. This is necessary to
   495                     // pick up the contents of the file chooser text field.
   545                     // pick up the contents of the file chooser text field.
   496                     // This will trigger an APPROVE_SELECTION action.
   546                     // This will trigger an APPROVE_SELECTION action.
   497                     ((BasicFileChooserUI)ui).getApproveSelectionAction().actionPerformed(null);
   547                     ((BasicFileChooserUI) ui).getApproveSelectionAction().
       
   548                             actionPerformed(null);
   498                 } else {
   549                 } else {
   499                     next();
   550                     next();
   500                 }
   551                 }
   501             } else if (src == closeButton) {
   552             } else if (src == closeButton) {
   502                 close();
   553                 close();
   503             } else if (cmd == APPROVE_SELECTION) {
   554             } else if (APPROVE_SELECTION.equals(cmd)) {
   504                 next();
   555                 next();
   505             } else if (cmd == CANCEL_SELECTION) {
   556             } else if (CANCEL_SELECTION.equals(cmd)) {
   506                 close();
   557                 close();
   507             }
   558             }
   508         }
   559         }
   509 
   560 
   510         private void back() {
   561         private void back() {
   526 
   577 
   527         private void close() {
   578         private void close() {
   528             setVisible(false);
   579             setVisible(false);
   529         }
   580         }
   530 
   581 
       
   582         @Override
   531         public void dispose() {
   583         public void dispose() {
   532             chooser.removeActionListener(this);
   584             chooser.removeActionListener(this);
   533 
   585 
   534             // The chooser is hidden by CardLayout on remove
   586             // The chooser is hidden by CardLayout on remove
   535             // so fix it here
   587             // so fix it here
   540         }
   592         }
   541     }
   593     }
   542 
   594 
   543     private String getResultString() {
   595     private String getResultString() {
   544         String resultString;
   596         String resultString;
   545         String filter = chooser.getFileFilter().getDescription();
   597         String filter;
       
   598         if (chooser.getFileFilter() == null) {
       
   599             filter = "";
       
   600         } else {
       
   601             filter = chooser.getFileFilter().getDescription();
       
   602         }
   546         String path = null;
   603         String path = null;
   547         boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);
   604         boolean isDirMode = (chooser.getFileSelectionMode() == DIRECTORIES_ONLY);
   548         boolean isMulti = chooser.isMultiSelectionEnabled();
   605         boolean isMulti = chooser.isMultiSelectionEnabled();
   549 
   606 
   550         if (isMulti) {
   607         if (isMulti) {
   551             File [] files = chooser.getSelectedFiles();
   608             File[] files = chooser.getSelectedFiles();
   552             if (files != null && files.length > 0) {
   609             if (files != null && files.length > 0) {
   553                 path = "";
   610                 path = "";
   554                 for (File file : files) {
   611                 for (File file : files) {
   555                     path = path + "<br>" + file.getPath();
   612                     path = path + "<br>" + file.getPath();
   556                 }
   613                 }
   563         }
   620         }
   564         if (path != null) {
   621         if (path != null) {
   565             path = path.replace(" ", "&nbsp;");
   622             path = path.replace(" ", "&nbsp;");
   566             filter = filter.replace(" ", "&nbsp;");
   623             filter = filter.replace(" ", "&nbsp;");
   567             resultString =
   624             resultString =
   568                 "<html>You chose " + (isMulti ? "these" : "this") + " " +
   625                     "<html>You chose " + (isMulti ? "these" : "this") + " " + (isDirMode ? (isMulti
   569                 (isDirMode ? (isMulti ? "directories" : "directory")
   626                     ? "directories" : "directory")
   570                            : (isMulti ? "files" : "file")) +
   627                     : (isMulti ? "files" : "file")) + ": <code>" + path
   571                 ": <code>" + path +
   628                     + "</code><br><br>with filter: <br><code>" + filter;
   572                 "</code><br><br>with filter: <br><code>" + filter;
       
   573         } else {
   629         } else {
   574             resultString = "Nothing was chosen";
   630             resultString = "Nothing was chosen";
   575         }
   631         }
   576         return resultString;
   632         return resultString;
   577     }
   633     }
   578 
   634 
   579 
   635 
   580 
       
   581 
       
   582     /** An ActionListener that listens to the radio buttons. */
   636     /** An ActionListener that listens to the radio buttons. */
   583     private class OptionListener implements ActionListener {
   637     private class OptionListener implements ActionListener {
       
   638 
   584         public void actionPerformed(ActionEvent e) {
   639         public void actionPerformed(ActionEvent e) {
   585             JComponent c = (JComponent) e.getSource();
   640             JComponent c = (JComponent) e.getSource();
   586             boolean selected = false;
   641             boolean selected = false;
   587             if (c instanceof JToggleButton) {
   642             if (c instanceof JToggleButton) {
   588                 selected = ((JToggleButton)c).isSelected();
   643                 selected = ((JToggleButton) c).isSelected();
   589             }
   644             }
   590 
   645 
   591             if (c == openRadioButton) {
   646             if (c == openRadioButton) {
   592                 chooser.setDialogType(OPEN_DIALOG);
   647                 chooser.setDialogType(OPEN_DIALOG);
   593                 customField.setEnabled(false);
   648                 customField.setEnabled(false);
   610                 repaint();
   665                 repaint();
   611             } else if (c == showAllFilesFilterCheckBox) {
   666             } else if (c == showAllFilesFilterCheckBox) {
   612                 chooser.setAcceptAllFileFilterUsed(selected);
   667                 chooser.setAcceptAllFileFilterUsed(selected);
   613             } else if (c == showImageFilesFilterCheckBox) {
   668             } else if (c == showImageFilesFilterCheckBox) {
   614                 resetFileFilters(selected,
   669                 resetFileFilters(selected,
   615                                  showFullDescriptionCheckBox.isSelected());
   670                         showFullDescriptionCheckBox.isSelected());
   616                 showFullDescriptionCheckBox.setEnabled(selected);
   671                 showFullDescriptionCheckBox.setEnabled(selected);
   617             } else if (c == setHiddenCheckBox) {
   672             } else if (c == setHiddenCheckBox) {
   618                 chooser.setFileHidingEnabled(!selected);
   673                 chooser.setFileHidingEnabled(!selected);
   619             } else if (c == accessoryCheckBox) {
   674             } else if (c == accessoryCheckBox) {
   620                 if (selected) {
   675                 if (selected) {
   635                     // Restore default behaviour
   690                     // Restore default behaviour
   636                     chooser.setFileSystemView(FileSystemView.getFileSystemView());
   691                     chooser.setFileSystemView(FileSystemView.getFileSystemView());
   637                 }
   692                 }
   638             } else if (c == showFullDescriptionCheckBox) {
   693             } else if (c == showFullDescriptionCheckBox) {
   639                 resetFileFilters(showImageFilesFilterCheckBox.isSelected(),
   694                 resetFileFilters(showImageFilesFilterCheckBox.isSelected(),
   640                                  selected);
   695                         selected);
   641             } else if (c == justFilesRadioButton) {
   696             } else if (c == justFilesRadioButton) {
   642                 chooser.setFileSelectionMode(FILES_ONLY);
   697                 chooser.setFileSelectionMode(FILES_ONLY);
   643             } else if (c == justDirectoriesRadioButton) {
   698             } else if (c == justDirectoriesRadioButton) {
   644                 chooser.setFileSelectionMode(DIRECTORIES_ONLY);
   699                 chooser.setFileSelectionMode(DIRECTORIES_ONLY);
   645             } else if (c == bothFilesAndDirectoriesRadioButton) {
   700             } else if (c == bothFilesAndDirectoriesRadioButton) {
   651             } else if (c == multiSelectionRadioButton) {
   706             } else if (c == multiSelectionRadioButton) {
   652                 if (selected) {
   707                 if (selected) {
   653                     chooser.setMultiSelectionEnabled(true);
   708                     chooser.setMultiSelectionEnabled(true);
   654                 }
   709                 }
   655             } else if (c == lafComboBox) {
   710             } else if (c == lafComboBox) {
   656                 SupportedLaF supportedLaF = ((SupportedLaF)lafComboBox.getSelectedItem());
   711                 SupportedLaF supportedLaF = ((SupportedLaF) lafComboBox.
       
   712                         getSelectedItem());
   657                 LookAndFeel laf = supportedLaF.laf;
   713                 LookAndFeel laf = supportedLaF.laf;
   658                 try {
   714                 try {
   659                     UIManager.setLookAndFeel(laf);
   715                     UIManager.setLookAndFeel(laf);
   660                     SwingUtilities.updateComponentTreeUI(frame);
   716                     SwingUtilities.updateComponentTreeUI(frame);
   661                     if(chooser != null) {
   717                     if (chooser != null) {
   662                         SwingUtilities.updateComponentTreeUI(chooser);
   718                         SwingUtilities.updateComponentTreeUI(chooser);
   663                     }
   719                     }
   664                     frame.pack();
   720                     frame.pack();
   665                 } catch (UnsupportedLookAndFeelException exc) {
   721                 } catch (UnsupportedLookAndFeelException exc) {
   666                     // This should not happen because we already checked
   722                     // This should not happen because we already checked
   667                     ((DefaultComboBoxModel)lafComboBox.getModel()).removeElement(supportedLaF);
   723                     ((DefaultComboBoxModel) lafComboBox.getModel()).
   668                 }
   724                             removeElement(supportedLaF);
   669             }
   725                 }
   670 
   726             }
   671         }
   727 
   672     }
   728         }
   673 
   729     }
   674     private class FilePreviewer extends JComponent implements PropertyChangeListener {
   730 
       
   731 
       
   732     private class FilePreviewer extends JComponent implements
       
   733             PropertyChangeListener {
       
   734 
   675         ImageIcon thumbnail = null;
   735         ImageIcon thumbnail = null;
   676 
   736 
       
   737         @SuppressWarnings("LeakingThisInConstructor")
   677         public FilePreviewer(JFileChooser fc) {
   738         public FilePreviewer(JFileChooser fc) {
   678             setPreferredSize(new Dimension(100, 50));
   739             setPreferredSize(new Dimension(100, 50));
   679             fc.addPropertyChangeListener(this);
   740             fc.addPropertyChangeListener(this);
   680         }
   741         }
   681 
   742 
   682         public void loadImage(File f) {
   743         public void loadImage(File f) {
   683             if (f == null) {
   744             if (f == null) {
   684                 thumbnail = null;
   745                 thumbnail = null;
   685             } else {
   746             } else {
   686                 ImageIcon tmpIcon = new ImageIcon(f.getPath());
   747                 ImageIcon tmpIcon = new ImageIcon(f.getPath());
   687                 if(tmpIcon.getIconWidth() > 90) {
   748                 if (tmpIcon.getIconWidth() > 90) {
   688                     thumbnail = new ImageIcon(
   749                     thumbnail = new ImageIcon(
   689                         tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
   750                             tmpIcon.getImage().getScaledInstance(90, -1,
       
   751                             Image.SCALE_DEFAULT));
   690                 } else {
   752                 } else {
   691                     thumbnail = tmpIcon;
   753                     thumbnail = tmpIcon;
   692                 }
   754                 }
   693             }
   755             }
   694         }
   756         }
   695 
   757 
   696         public void propertyChange(PropertyChangeEvent e) {
   758         public void propertyChange(PropertyChangeEvent e) {
   697             String prop = e.getPropertyName();
   759             String prop = e.getPropertyName();
   698             if (prop == SELECTED_FILE_CHANGED_PROPERTY) {
   760             if (SELECTED_FILE_CHANGED_PROPERTY.equals(prop)) {
   699                 if(isShowing()) {
   761                 if (isShowing()) {
   700                     loadImage((File) e.getNewValue());
   762                     loadImage((File) e.getNewValue());
   701                     repaint();
   763                     repaint();
   702                 }
   764                 }
   703             }
   765             }
   704         }
   766         }
   705 
   767 
       
   768         @Override
   706         public void paint(Graphics g) {
   769         public void paint(Graphics g) {
   707             if(thumbnail != null) {
   770             if (thumbnail != null) {
   708                 int x = getWidth()/2 - thumbnail.getIconWidth()/2;
   771                 int x = getWidth() / 2 - thumbnail.getIconWidth() / 2;
   709                 int y = getHeight()/2 - thumbnail.getIconHeight()/2;
   772                 int y = getHeight() / 2 - thumbnail.getIconHeight() / 2;
   710                 if(y < 0) {
   773                 if (y < 0) {
   711                     y = 0;
   774                     y = 0;
   712                 }
   775                 }
   713 
   776 
   714                 if(x < 5) {
   777                 if (x < 5) {
   715                     x = 5;
   778                     x = 5;
   716                 }
   779                 }
   717                 thumbnail.paintIcon(this, g, x, y);
   780                 thumbnail.paintIcon(this, g, x, y);
   718             }
   781             }
   719         }
   782         }
   720     }
   783     }
   721 
   784 
   722     public static void main(String s[]) {
   785     public static void main(String s[]) {
   723         /*
   786         try {
   724            NOTE: By default, the look and feel will be set to the
   787             SwingUtilities.invokeAndWait(new Runnable() {
   725            Cross Platform Look and Feel (which is currently Metal).
   788 
   726            The user may someday be able to override the default
   789                 public void run() {
   727            via a system property. If you as the developer want to
   790                     /*
   728            be sure that a particular L&F is set, you can do so
   791                      * NOTE: By default, the look and feel will be set to the
   729            by calling UIManager.setLookAndFeel(). For example, the
   792                      * Cross Platform Look and Feel (which is currently Metal).
   730            first code snippet below forcibly sets the UI to be the
   793                      * The following code tries to set the Look and Feel to Nimbus.
   731            System Look and Feel. The second code snippet forcibly
   794                      * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/nimbus.html
   732            sets the look and feel to the Cross Platform L&F.
   795                      */
   733 
   796                     try {
   734            Snippet 1:
   797                         for (LookAndFeelInfo info : UIManager.
   735            try {
   798                                 getInstalledLookAndFeels()) {
   736               UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
   799                             if (NIMBUS_LAF_NAME.equals(info.getName())) {
   737            } catch (Exception exc) {
   800                                 UIManager.setLookAndFeel(info.getClassName());
   738               System.err.println("Error loading L&F: " + exc);
   801                                 break;
   739            }
   802                             }
   740 
   803                         }
   741            Snippet 2:
   804                     } catch (Exception ignored) {
   742            try {
   805                     }
   743               UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
   806 
   744            } catch (Exception exc) {
   807                     FileChooserDemo panel = new FileChooserDemo();
   745               System.err.println("Error loading L&F: " + exc);
   808 
   746            }
   809                     frame = new JFrame("FileChooserDemo");
   747         */
   810                     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
   748 
   811                     frame.getContentPane().add("Center", panel);
   749         FileChooserDemo panel = new FileChooserDemo();
   812                     frame.pack();
   750 
   813                     frame.setVisible(true);
   751         frame = new JFrame("FileChooserDemo");
   814                 }
   752         frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
   815             });
   753         frame.getContentPane().add("Center", panel);
   816         } catch (InterruptedException ex) {
   754         frame.pack();
   817             Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
   755         frame.setVisible(true);
   818                     null,
   756     }
   819                     ex);
       
   820         } catch (InvocationTargetException ex) {
       
   821             Logger.getLogger(FileChooserDemo.class.getName()).log(Level.SEVERE,
       
   822                     null,
       
   823                     ex);
       
   824         }
       
   825     }
       
   826 
   757 
   827 
   758     private static class InsetPanel extends JPanel {
   828     private static class InsetPanel extends JPanel {
       
   829 
   759         Insets i;
   830         Insets i;
       
   831 
   760         InsetPanel(Insets i) {
   832         InsetPanel(Insets i) {
   761             this.i = i;
   833             this.i = i;
   762         }
   834         }
       
   835 
       
   836         @Override
   763         public Insets getInsets() {
   837         public Insets getInsets() {
   764             return i;
   838             return i;
   765         }
   839         }
   766     }
   840     }
   767 }
   841 }