KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > util > swing > FileSelectorComponent


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  *END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.util.swing;
35
36 import javax.swing.*;
37 import javax.swing.filechooser.FileFilter JavaDoc;
38 import java.awt.*;
39 import java.awt.event.ActionEvent JavaDoc;
40 import java.awt.event.ActionListener JavaDoc;
41 import java.awt.event.FocusListener JavaDoc;
42 import java.awt.event.FocusEvent JavaDoc;
43 import java.io.*;
44
45 /** A JPanel with a text box and a "..." button used to select a file or directory. The file name is editable in the
46  * text box, and a JFileChooser is displayed if the user clicks the "..." button.
47  * TODO: make this inherit from FileSelectorStringComponent or factor the common code into an abstract class! Duplicated code!
48  *
49  * @version $Id: FileSelectorComponent.java 4031 2006-11-15 22:09:06Z rcartwright $
50  */

51 public class FileSelectorComponent extends JPanel {
52   
53   /** The default number of columns for the text box. */
54   public static final int DEFAULT_NUM_COLS = 30;
55
56   /** The default font size for the text box. */
57   public static final float DEFAULT_FONT_SIZE = 10f;
58
59   /** The parent frame of this component. */
60   protected final Frame _parent;
61
62   /** Text field with the name of the selected file. */
63   protected final JTextField _fileField;
64
65   /** "..." button to open the file chooser. */
66   protected final JButton _chooserButton;
67
68   /** File chooser to open when clicking the "..." button. */
69   protected final JFileChooser _chooser;
70
71   /** File filter to use in the chooser. */
72   protected FileFilter JavaDoc _fileFilter;
73   
74   /** The current file */
75   protected File _file;
76   
77   /** True if file must exist. */
78   protected boolean _mustExist;
79
80   /** Creates a new FileSelectorComponent with default dimensions.
81    *
82    * @param parent Parent of this component.
83    * @param chooser File chooser to display from the "..." button.
84    */

85   public FileSelectorComponent(Frame parent, JFileChooser chooser) {
86     this(parent, chooser, DEFAULT_NUM_COLS, DEFAULT_FONT_SIZE, true);
87   }
88
89   /** Creates a new FileSelectorComponent.
90    *
91    * @param parent Parent of this component.
92    * @param chooser File chooser to display from the "..." button.
93    * @param numCols Number of columns to display in the text field
94    * @param fontSize Font size for the text field
95    */

96   public FileSelectorComponent(Frame parent, JFileChooser chooser, int numCols, float fontSize) {
97     this(parent, chooser, numCols, fontSize, true);
98   }
99   
100   /** Creates a new FileSelectorComponent.
101    *
102    * @param parent Parent of this component.
103    * @param chooser File chooser to display from the "..." button.
104    * @param numCols Number of columns to display in the text field
105    * @param fontSize Font size for the text field
106    * @param mustExist force selection of existing file
107    */

108   public FileSelectorComponent(Frame parent, JFileChooser chooser, int numCols, float fontSize, boolean mustExist) {
109     
110     _parent = parent;
111     _chooser = chooser;
112     _fileFilter = null;
113     _mustExist = mustExist;
114     
115     _fileField = new JTextField(numCols) {
116       public Dimension getMaximumSize() {
117         return new Dimension(Short.MAX_VALUE, super.getPreferredSize().height);
118       }
119     };
120     
121     _fileField.setFont(_fileField.getFont().deriveFont(fontSize));
122     _fileField.setPreferredSize(new Dimension(22, 22));
123     _fileField.addActionListener(new ActionListener JavaDoc() {
124       public void actionPerformed(ActionEvent JavaDoc e) { validateTextField(); }
125     });
126     
127     _fileField.addFocusListener(new FocusListener JavaDoc() {
128       public void focusGained(FocusEvent JavaDoc e) { /* validateTextField(); */ }
129       public void focusLost(FocusEvent JavaDoc e) { validateTextField(); }
130     });
131     
132     _chooserButton = new JButton("...");
133     _chooserButton.addActionListener(new ActionListener JavaDoc() {
134       public void actionPerformed(ActionEvent JavaDoc e) { _chooseFile(); }
135     });
136     
137     _chooserButton.setMaximumSize(new Dimension(22, 22));
138     _chooserButton.setMargin(new Insets(0, 5 ,0, 5));
139     
140     // Add components
141
this.setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
142     this.add(_fileField);
143     this.add(_chooserButton);
144   }
145
146   public void setEnabled(boolean isEnabled) {
147     _fileField.setEnabled(isEnabled);
148     _chooserButton.setEnabled(isEnabled);
149     super.setEnabled(isEnabled);
150   }
151
152   /** Returns the file text field. */
153   public JTextField getFileField() { return _fileField; }
154
155   /** Returns the file chooser. */
156   public JFileChooser getFileChooser() { return _chooser; }
157
158   /** Returns the file currently typed into the file field. */
159   public File getFileFromField() {
160     String JavaDoc txt = _fileField.getText().trim();
161     if (txt.equals("")) _file = null;
162     else _file = new File(txt);
163     
164     return _file;
165   }
166
167   /** Sets the text of the file field to be the given file.
168    * @param file File to display in the file field.
169    */

170   public void setFileField(File file) {
171     _file = file;
172     if (file != null && !file.getPath().equals("")) {
173       try {_file = file.getCanonicalFile(); }
174       catch(IOException e) { /* do nothing */ }
175     }
176     resetFileField();
177   }
178
179   public void resetFileField() {
180     if (_file == null) _fileField.setText("");
181     else {
182       _fileField.setText(_file.getPath());
183       _fileField.setCaretPosition(_fileField.getText().length());
184     }
185   }
186   
187   /** Sets the file filter to use. */
188   public void setFileFilter(FileFilter JavaDoc filter) { _fileFilter = filter; }
189
190   public void setToolTipText(String JavaDoc text) {
191     super.setToolTipText(text);
192     _fileField.setToolTipText(text);
193     _chooser.setToolTipText(text);
194   }
195   
196   /** Opens the file chooser to select a file, putting the result in the file field. */
197   private void _chooseFile() {
198     // Set the chooser to be in the right directory
199
if (_file != null && _file.exists()) {
200       _chooser.setCurrentDirectory(_file);
201       _chooser.setSelectedFile(_file);
202     }
203
204     // Apply the filter
205
if (_fileFilter != null) _chooser.setFileFilter(_fileFilter);
206
207     // Get the file from the chooser
208
int returnValue = _chooser.showDialog(_parent, null);
209     if (returnValue == JFileChooser.APPROVE_OPTION) {
210       File chosen = _chooser.getSelectedFile();
211       if (chosen != null) setFileField(chosen);
212     }
213   }
214    
215   // used so that the focus listener and the action listener do not
216
// both validate the incorrect text. This ensures that only the first
217
// one gets it.
218
// private boolean _validationInProgress = false;
219

220   /** The chooser method for the validation of filenames that are manually entered into the text field.
221    * @return False, if file does not exist. True, otherwise.
222    */

223   public boolean validateTextField() {
224 // if (_validationInProgress) return true;
225
// _validationInProgress = true;
226

227     String JavaDoc newValue = _fileField.getText().trim();
228     
229     File newFile = null;
230     if (!newValue.equals(""))
231       newFile = new File(newValue);
232     
233     if (newFile != null && _mustExist && !newFile.exists()) {
234       JOptionPane.showMessageDialog(_parent, "The file '"+ newValue + "'\nis invalid because it does not exist.",
235                                     "Invalid File Name", JOptionPane.ERROR_MESSAGE);
236       if (!_file.exists()) _file = null;
237       resetFileField(); // revert if not valid
238

239 // _validationInProgress = false;
240
return false;
241     }
242     else {
243       setFileField(newFile);
244 // _validationInProgress = false;
245
return true;
246     }
247   }
248 }
Popular Tags