FileChooserDemo.java  
1   /*
2    * @(#)FileChooserDemo.java 1.16 04/07/26
3    * 
4    * Copyright (c) 2004 Sun Microsystems, Inc. All Rights Reserved.
5    * 
6    * Redistribution and use in source and binary forms, with or without
7    * modification, are permitted provided that the following conditions are met:
8    * 
9    * -Redistribution of source code must retain the above copyright notice, this
10   *  list of conditions and the following disclaimer.
11   * 
12   * -Redistribution in binary form must reproduce the above copyright notice, 
13   *  this list of conditions and the following disclaimer in the documentation
14   *  and/or other materials provided with the distribution.
15   * 
16   * Neither the name of Sun Microsystems, Inc. or the names of contributors may 
17   * be used to endorse or promote products derived from this software without 
18   * specific prior written permission.
19   * 
20   * This software is provided "AS IS," without a warranty of any kind. ALL 
21   * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
22   * ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
23   * OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
24   * AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
25   * AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
26   * DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST 
27   * REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, 
28   * INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY 
29   * OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, 
30   * EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
31   * 
32   * You acknowledge that this software is not designed, licensed or intended
33   * for use in the design, construction, operation or maintenance of any
34   * nuclear facility.
35   */
36  
37  /*
38   * @(#)FileChooserDemo.java 1.16 04/07/26
39   */
40  
41  
42  import javax.swing.*;
43  import javax.swing.event.*;
44  import javax.swing.text.*;
45  import javax.swing.border.*;
46  import javax.swing.colorchooser.*;
47  import javax.swing.filechooser.*;
48  import javax.accessibility.*;
49  
50  import java.awt.*;
51  import java.awt.event.*;
52  import java.beans.*;
53  import java.util.*;
54  import java.io.*;
55  import java.applet.*;
56  import java.net.*;
57  
58  /**
59   * JFileChooserDemo
60   *
61   * @version 1.1 07/16/99
62   * @author Jeff Dinkins
63   */
64  public class FileChooserDemo extends DemoModule {
65      JLabel theImage;
66      Icon jpgIcon; 
67      Icon gifIcon;
68  
69      /**
70       * main method allows us to run as a standalone demo.
71       */
72      public static void main(String[] args) {
73      FileChooserDemo demo = new FileChooserDemo(null);
74      demo.mainImpl();
75      }
76  
77      /**
78       * FileChooserDemo Constructor
79       */
80      public FileChooserDemo(SwingSet2 swingset) {
81      // Set the title for this demo, and an icon used to represent this
82      // demo inside the SwingSet2 app.
83      super(swingset, "FileChooserDemo", "toolbar/JFileChooser.gif");
84      createFileChooserDemo();
85      }
86  
87      public void createFileChooserDemo() {
88      theImage = new JLabel("");
89      jpgIcon = createImageIcon("filechooser/jpgIcon.jpg", "jpg image");
90      gifIcon = createImageIcon("filechooser/gifIcon.gif", "gif image");
91  
92      JPanel demoPanel = getDemoPanel();
93      demoPanel.setLayout(new BoxLayout(demoPanel, BoxLayout.Y_AXIS));
94  
95      JPanel innerPanel = new JPanel();
96      innerPanel.setLayout(new BoxLayout(innerPanel, BoxLayout.X_AXIS));
97  
98      demoPanel.add(Box.createRigidArea(VGAP20));
99      demoPanel.add(innerPanel);
100     demoPanel.add(Box.createRigidArea(VGAP20));
101 
102     innerPanel.add(Box.createRigidArea(HGAP20));
103 
104     // Create a panel to hold buttons
105     JPanel buttonPanel = new JPanel() {
106         public Dimension getMaximumSize() {
107         return new Dimension(getPreferredSize().width, super.getMaximumSize().height);
108         }
109     };
110     buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.Y_AXIS));
111 
112     buttonPanel.add(Box.createRigidArea(VGAP15));
113     buttonPanel.add(createPlainFileChooserButton());
114     buttonPanel.add(Box.createRigidArea(VGAP15));
115     buttonPanel.add(createPreviewFileChooserButton());
116     buttonPanel.add(Box.createRigidArea(VGAP15));
117     buttonPanel.add(createCustomFileChooserButton());
118     buttonPanel.add(Box.createVerticalGlue());
119 
120     // Create a panel to hold the image
121     JPanel imagePanel = new JPanel();
122     imagePanel.setLayout(new BorderLayout());
123     imagePanel.setBorder(new BevelBorder(BevelBorder.LOWERED));
124     JScrollPane scroller = new JScrollPane(theImage);
125         scroller.getVerticalScrollBar().setUnitIncrement(10);
126         scroller.getHorizontalScrollBar().setUnitIncrement(10);
127     imagePanel.add(scroller, BorderLayout.CENTER);
128 
129     // add buttons and image panels to inner panel
130     innerPanel.add(buttonPanel);
131     innerPanel.add(Box.createRigidArea(HGAP30));
132     innerPanel.add(imagePanel);
133     innerPanel.add(Box.createRigidArea(HGAP20));
134     }
135 
136     public JFileChooser createFileChooser() {
137     // create a filechooser
138     JFileChooser fc = new JFileChooser();
139         if (getSwingSet2() != null && getSwingSet2().isDragEnabled()) {
140             fc.setDragEnabled(true);
141         }
142     
143     // set the current directory to be the images directory
144     File swingFile = new File("resources/images/About.jpg");
145     if(swingFile.exists()) {
146         fc.setCurrentDirectory(swingFile);
147         fc.setSelectedFile(swingFile);
148     }
149     
150     return fc;
151     }
152 
153 
154     public JButton createPlainFileChooserButton() {
155     Action a = new AbstractAction(getString("FileChooserDemo.plainbutton")) {
156         public void actionPerformed(ActionEvent e) {
157         JFileChooser fc = createFileChooser();
158 
159         // show the filechooser
160         int result = fc.showOpenDialog(getDemoPanel());
161         
162         // if we selected an image, load the image
163         if(result == JFileChooser.APPROVE_OPTION) {
164             loadImage(fc.getSelectedFile().getPath());
165         }
166         }
167     };
168     return createButton(a);
169     }
170 
171     public JButton createPreviewFileChooserButton() {
172     Action a = new AbstractAction(getString("FileChooserDemo.previewbutton")) {
173         public void actionPerformed(ActionEvent e) {
174         JFileChooser fc = createFileChooser();
175 
176         // Add filefilter & fileview
177         ExampleFileFilter filter = new ExampleFileFilter(
178             new String[] {"jpg", "gif"}, getString("FileChooserDemo.filterdescription")
179         );
180         ExampleFileView fileView = new ExampleFileView();
181         fileView.putIcon("jpg", jpgIcon);
182         fileView.putIcon("gif", gifIcon);
183         fc.setFileView(fileView);
184         fc.addChoosableFileFilter(filter);
185         fc.setFileFilter(filter);
186         
187         // add preview accessory
188         fc.setAccessory(new FilePreviewer(fc));
189 
190         // show the filechooser
191         int result = fc.showOpenDialog(getDemoPanel());
192         
193         // if we selected an image, load the image
194         if(result == JFileChooser.APPROVE_OPTION) {
195             loadImage(fc.getSelectedFile().getPath());
196         }
197         }
198     };
199     return createButton(a);
200     }
201 
202     JDialog dialog;
203     JFileChooser fc;
204 
205     public JButton createCustomFileChooserButton() {
206     Action a = new AbstractAction(getString("FileChooserDemo.custombutton")) {
207         public void actionPerformed(ActionEvent e) {
208         fc = createFileChooser();
209 
210         // Add filefilter & fileview
211         ExampleFileFilter filter = new ExampleFileFilter(
212             new String[] {"jpg", "gif"}, getString("FileChooserDemo.filterdescription")
213         );
214         ExampleFileView fileView = new ExampleFileView();
215         fileView.putIcon("jpg", jpgIcon);
216         fileView.putIcon("gif", gifIcon);
217         fc.setFileView(fileView);
218         fc.addChoosableFileFilter(filter);
219 
220         // add preview accessory
221         fc.setAccessory(new FilePreviewer(fc));
222 
223         // remove the approve/cancel buttons
224         fc.setControlButtonsAreShown(false);
225 
226         // make custom controls
227         //wokka
228         JPanel custom = new JPanel();
229         custom.setLayout(new BoxLayout(custom, BoxLayout.Y_AXIS));
230         custom.add(Box.createRigidArea(VGAP10));
231         JLabel description = new JLabel(getString("FileChooserDemo.description"));
232         description.setAlignmentX(JLabel.CENTER_ALIGNMENT);
233         custom.add(description);
234         custom.add(Box.createRigidArea(VGAP10));
235         custom.add(fc);
236 
237         Action okAction = createOKAction();
238         fc.addActionListener(okAction);
239 
240         JPanel buttons = new JPanel();
241         buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
242         buttons.add(Box.createRigidArea(HGAP10));
243         buttons.add(createImageButton(createFindAction()));
244         buttons.add(Box.createRigidArea(HGAP10));
245         buttons.add(createButton(createAboutAction()));
246         buttons.add(Box.createRigidArea(HGAP10));
247         buttons.add(createButton(okAction));
248         buttons.add(Box.createRigidArea(HGAP10));
249         buttons.add(createButton(createCancelAction()));
250         buttons.add(Box.createRigidArea(HGAP10));
251         buttons.add(createImageButton(createHelpAction()));
252         buttons.add(Box.createRigidArea(HGAP10));
253 
254         custom.add(buttons);
255         custom.add(Box.createRigidArea(VGAP10));
256         
257         // show the filechooser
258         Frame parent = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, getDemoPanel());
259         dialog = new JDialog(parent, getString("FileChooserDemo.dialogtitle"), true);
260                 dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
261         dialog.getContentPane().add(custom, BorderLayout.CENTER);
262         dialog.pack();
263         dialog.setLocationRelativeTo(getDemoPanel());
264         dialog.show();
265         }
266     };
267     return createButton(a);
268     }
269 
270     public Action createAboutAction() {
271     return new AbstractAction(getString("FileChooserDemo.about")) {
272         public void actionPerformed(ActionEvent e) {
273         File file = fc.getSelectedFile();
274         String text;
275         if(file == null) {
276             text = getString("FileChooserDemo.nofileselected");
277         } else {
278             text = "<html>" + getString("FileChooserDemo.thefile");
279             text += "<br><font color=green>" + file.getName() + "</font><br>";
280             text += getString("FileChooserDemo.isprobably") + "</html>";
281         }
282         JOptionPane.showMessageDialog(getDemoPanel(), text);
283         }
284     };
285     }
286 
287     public Action createOKAction() {
288     return new AbstractAction(getString("FileChooserDemo.ok")) {
289         public void actionPerformed(ActionEvent e) {
290         dialog.dispose();
291         if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)
292             && fc.getSelectedFile() != null) {
293 
294             loadImage(fc.getSelectedFile().getPath());
295         }
296         }
297     };
298     }
299 
300     public Action createCancelAction() {
301     return new AbstractAction(getString("FileChooserDemo.cancel")) {
302         public void actionPerformed(ActionEvent e) {
303         dialog.dispose();
304         }
305     };
306     }
307 
308     public Action createFindAction() {
309     Icon icon = createImageIcon("filechooser/find.gif", getString("FileChooserDemo.find"));
310     return new AbstractAction("", icon) {
311         public void actionPerformed(ActionEvent e) {
312                 String result = JOptionPane.showInputDialog(getDemoPanel(), getString("FileChooserDemo.findquestion"));
313         if (result != null) {
314             JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.findresponse"));
315         }
316         }
317     };
318     }
319 
320     public Action createHelpAction() {
321     Icon icon = createImageIcon("filechooser/help.gif", getString("FileChooserDemo.help"));
322     return new AbstractAction("", icon) {
323         public void actionPerformed(ActionEvent e) {
324         JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.helptext"));
325         }
326     };
327     }
328     
329     class MyImageIcon extends ImageIcon {
330     public MyImageIcon(String filename) {
331         super(filename);
332     };
333     public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
334         g.setColor(Color.white);
335         g.fillRect(0,0, c.getWidth(), c.getHeight());
336         if(getImageObserver() == null) {
337         g.drawImage(
338             getImage(),
339             c.getWidth()/2 - getIconWidth()/2,
340             c.getHeight()/2 - getIconHeight()/2,
341             c
342         );
343         } else {
344         g.drawImage(
345             getImage(),
346             c.getWidth()/2 - getIconWidth()/2,
347             c.getHeight()/2 - getIconHeight()/2,
348             getImageObserver()
349         );
350         }
351     }
352     }
353 
354     public void loadImage(String filename) {
355     theImage.setIcon(new MyImageIcon(filename));
356     }
357 
358     public JButton createButton(Action a) {
359     JButton b = new JButton(a) {
360         public Dimension getMaximumSize() {
361         int width = Short.MAX_VALUE;
362         int height = super.getMaximumSize().height;
363         return new Dimension(width, height);
364         }
365     };
366     return b;
367     }
368 
369     public JButton createImageButton(Action a) {
370     JButton b = new JButton(a);
371     b.setMargin(new Insets(0,0,0,0));
372     return b;
373     }
374 }
375 
376 class FilePreviewer extends JComponent implements PropertyChangeListener {
377     ImageIcon thumbnail = null;
378     
379     public FilePreviewer(JFileChooser fc) {
380     setPreferredSize(new Dimension(100, 50));
381     fc.addPropertyChangeListener(this);
382     setBorder(new BevelBorder(BevelBorder.LOWERED));
383     }
384     
385     public void loadImage(File f) {
386         if (f == null) {
387             thumbnail = null;
388         } else {
389         ImageIcon tmpIcon = new ImageIcon(f.getPath());
390         if(tmpIcon.getIconWidth() > 90) {
391         thumbnail = new ImageIcon(
392             tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
393         } else {
394         thumbnail = tmpIcon;
395         }
396     }
397     }
398     
399     public void propertyChange(PropertyChangeEvent e) {
400     String prop = e.getPropertyName();
401     if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
402         if(isShowing()) {
403                 loadImage((File) e.getNewValue());
404         repaint();
405         }
406     }
407     }
408     
409     public void paint(Graphics g) {
410     super.paint(g);
411     if(thumbnail != null) {
412         int x = getWidth()/2 - thumbnail.getIconWidth()/2;
413         int y = getHeight()/2 - thumbnail.getIconHeight()/2;
414         if(y < 0) {
415         y = 0;
416         }
417         
418         if(x < 5) {
419         x = 5;
420         }
421         thumbnail.paintIcon(this, g, x, y);
422     }
423     }
424 }
425 
426