KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > FileChooserDemo


1 /*
2  * @(#)FileChooserDemo.java 1.18 06/02/03
3  *
4  * Copyright (c) 2006 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.18 06/02/03
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.18 02/03/06
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 JavaDoc[] 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
javax.swing.filechooser.FileFilter JavaDoc filter = createFileFilter(
178                     getString("FileChooserDemo.filterdescription"),
179                     "jpg", "gif");
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     private javax.swing.filechooser.FileFilter JavaDoc createFileFilter(
206             String JavaDoc description, String JavaDoc...extensions) {
207         description = createFileNameFilterDescriptionFromExtensions(
208                     description, extensions);
209         return new FileNameExtensionFilter(description, extensions);
210     }
211
212     private String JavaDoc createFileNameFilterDescriptionFromExtensions(
213             String JavaDoc description, String JavaDoc[] extensions) {
214         String JavaDoc fullDescription = (description == null) ?
215                 "(" : description + " (";
216         // build the description from the extension list
217
fullDescription += "." + extensions[0];
218         for (int i = 1; i < extensions.length; i++) {
219             fullDescription += ", .";
220             fullDescription += extensions[i];
221         }
222         fullDescription += ")";
223         return fullDescription;
224     }
225
226     public JButton createCustomFileChooserButton() {
227     Action a = new AbstractAction(getString("FileChooserDemo.custombutton")) {
228         public void actionPerformed(ActionEvent e) {
229         fc = createFileChooser();
230
231         // Add filefilter & fileview
232
javax.swing.filechooser.FileFilter JavaDoc filter = createFileFilter(
233                     getString("FileChooserDemo.filterdescription"),
234                     "jpg", "gif");
235         ExampleFileView fileView = new ExampleFileView();
236         fileView.putIcon("jpg", jpgIcon);
237         fileView.putIcon("gif", gifIcon);
238         fc.setFileView(fileView);
239         fc.addChoosableFileFilter(filter);
240
241         // add preview accessory
242
fc.setAccessory(new FilePreviewer(fc));
243
244         // remove the approve/cancel buttons
245
fc.setControlButtonsAreShown(false);
246
247         // make custom controls
248
//wokka
249
JPanel custom = new JPanel();
250         custom.setLayout(new BoxLayout(custom, BoxLayout.Y_AXIS));
251         custom.add(Box.createRigidArea(VGAP10));
252         JLabel description = new JLabel(getString("FileChooserDemo.description"));
253         description.setAlignmentX(JLabel.CENTER_ALIGNMENT);
254         custom.add(description);
255         custom.add(Box.createRigidArea(VGAP10));
256         custom.add(fc);
257
258         Action okAction = createOKAction();
259         fc.addActionListener(okAction);
260
261         JPanel buttons = new JPanel();
262         buttons.setLayout(new BoxLayout(buttons, BoxLayout.X_AXIS));
263         buttons.add(Box.createRigidArea(HGAP10));
264         buttons.add(createImageButton(createFindAction()));
265         buttons.add(Box.createRigidArea(HGAP10));
266         buttons.add(createButton(createAboutAction()));
267         buttons.add(Box.createRigidArea(HGAP10));
268         buttons.add(createButton(okAction));
269         buttons.add(Box.createRigidArea(HGAP10));
270         buttons.add(createButton(createCancelAction()));
271         buttons.add(Box.createRigidArea(HGAP10));
272         buttons.add(createImageButton(createHelpAction()));
273         buttons.add(Box.createRigidArea(HGAP10));
274
275         custom.add(buttons);
276         custom.add(Box.createRigidArea(VGAP10));
277         
278         // show the filechooser
279
Frame parent = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, getDemoPanel());
280         dialog = new JDialog(parent, getString("FileChooserDemo.dialogtitle"), true);
281                 dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
282         dialog.getContentPane().add(custom, BorderLayout.CENTER);
283         dialog.pack();
284         dialog.setLocationRelativeTo(getDemoPanel());
285         dialog.show();
286         }
287     };
288     return createButton(a);
289     }
290
291     public Action createAboutAction() {
292     return new AbstractAction(getString("FileChooserDemo.about")) {
293         public void actionPerformed(ActionEvent e) {
294         File file = fc.getSelectedFile();
295         String JavaDoc text;
296         if(file == null) {
297             text = getString("FileChooserDemo.nofileselected");
298         } else {
299             text = "<html>" + getString("FileChooserDemo.thefile");
300             text += "<br><font color=green>" + file.getName() + "</font><br>";
301             text += getString("FileChooserDemo.isprobably") + "</html>";
302         }
303         JOptionPane.showMessageDialog(getDemoPanel(), text);
304         }
305     };
306     }
307
308     public Action createOKAction() {
309     return new AbstractAction(getString("FileChooserDemo.ok")) {
310         public void actionPerformed(ActionEvent e) {
311         dialog.dispose();
312         if (!e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION)
313             && fc.getSelectedFile() != null) {
314
315             loadImage(fc.getSelectedFile().getPath());
316         }
317         }
318     };
319     }
320
321     public Action createCancelAction() {
322     return new AbstractAction(getString("FileChooserDemo.cancel")) {
323         public void actionPerformed(ActionEvent e) {
324         dialog.dispose();
325         }
326     };
327     }
328
329     public Action createFindAction() {
330     Icon icon = createImageIcon("filechooser/find.gif", getString("FileChooserDemo.find"));
331     return new AbstractAction("", icon) {
332         public void actionPerformed(ActionEvent e) {
333                 String JavaDoc result = JOptionPane.showInputDialog(getDemoPanel(), getString("FileChooserDemo.findquestion"));
334         if (result != null) {
335             JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.findresponse"));
336         }
337         }
338     };
339     }
340
341     public Action createHelpAction() {
342     Icon icon = createImageIcon("filechooser/help.gif", getString("FileChooserDemo.help"));
343     return new AbstractAction("", icon) {
344         public void actionPerformed(ActionEvent e) {
345         JOptionPane.showMessageDialog(getDemoPanel(), getString("FileChooserDemo.helptext"));
346         }
347     };
348     }
349     
350     class MyImageIcon extends ImageIcon {
351     public MyImageIcon(String JavaDoc filename) {
352         super(filename);
353     };
354     public synchronized void paintIcon(Component c, Graphics g, int x, int y) {
355         g.setColor(Color.white);
356         g.fillRect(0,0, c.getWidth(), c.getHeight());
357         if(getImageObserver() == null) {
358         g.drawImage(
359             getImage(),
360             c.getWidth()/2 - getIconWidth()/2,
361             c.getHeight()/2 - getIconHeight()/2,
362             c
363         );
364         } else {
365         g.drawImage(
366             getImage(),
367             c.getWidth()/2 - getIconWidth()/2,
368             c.getHeight()/2 - getIconHeight()/2,
369             getImageObserver()
370         );
371         }
372     }
373     }
374
375     public void loadImage(String JavaDoc filename) {
376     theImage.setIcon(new MyImageIcon(filename));
377     }
378
379     public JButton createButton(Action a) {
380     JButton b = new JButton(a) {
381         public Dimension getMaximumSize() {
382         int width = Short.MAX_VALUE;
383         int height = super.getMaximumSize().height;
384         return new Dimension(width, height);
385         }
386     };
387     return b;
388     }
389
390     public JButton createImageButton(Action a) {
391     JButton b = new JButton(a);
392     b.setMargin(new Insets(0,0,0,0));
393     return b;
394     }
395 }
396
397 class FilePreviewer extends JComponent implements PropertyChangeListener {
398     ImageIcon thumbnail = null;
399     
400     public FilePreviewer(JFileChooser fc) {
401     setPreferredSize(new Dimension(100, 50));
402     fc.addPropertyChangeListener(this);
403     setBorder(new BevelBorder(BevelBorder.LOWERED));
404     }
405     
406     public void loadImage(File f) {
407         if (f == null) {
408             thumbnail = null;
409         } else {
410         ImageIcon tmpIcon = new ImageIcon(f.getPath());
411         if(tmpIcon.getIconWidth() > 90) {
412         thumbnail = new ImageIcon(
413             tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
414         } else {
415         thumbnail = tmpIcon;
416         }
417     }
418     }
419     
420     public void propertyChange(PropertyChangeEvent e) {
421     String JavaDoc prop = e.getPropertyName();
422     if(prop == JFileChooser.SELECTED_FILE_CHANGED_PROPERTY) {
423         if(isShowing()) {
424                 loadImage((File) e.getNewValue());
425         repaint();
426         }
427     }
428     }
429     
430     public void paint(Graphics g) {
431     super.paint(g);
432     if(thumbnail != null) {
433         int x = getWidth()/2 - thumbnail.getIconWidth()/2;
434         int y = getHeight()/2 - thumbnail.getIconHeight()/2;
435         if(y < 0) {
436         y = 0;
437         }
438         
439         if(x < 5) {
440         x = 5;
441         }
442         thumbnail.paintIcon(this, g, x, y);
443     }
444     }
445 }
446
447
Popular Tags