KickJava   Java API By Example, From Geeks To Geeks.

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


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 to select a file or directory. The file name is editable in the text
46  * box, and a JFileChooser is displayed if the user clicks the "..." button.
47  * @version $Id: DirectorySelectorComponent.java 3906 2006-07-19 22:26:45Z mgricken $
48  */

49 public class DirectorySelectorComponent extends JPanel {
50   
51   /** The default number of columns for the text box. */
52   public static final int DEFAULT_NUM_COLS = 30;
53
54   /** The default font size for the text box. */
55   public static final float DEFAULT_FONT_SIZE = 10f;
56
57   /** The parent component of this component. */
58   protected final Component _parent;
59
60   /** Text field with the name of the selected file. */
61   protected final JTextField _fileField;
62
63   /** "..." button to open the file chooser. */
64   protected final JButton _chooserButton;
65
66   /** File chooser to open when clicking the "..." button. */
67   protected final DirectoryChooser _chooser;
68
69   /** The current file */
70   protected File _file;
71   
72   /** true if the file specified must exist and a file that doesn't exist will be rejected. */
73   protected boolean _mustExist;
74   
75   /** Creates a new DirectorySelectorComponent with default dimensions whose file must exist.
76    * @param parent Parent of this component.
77    * @param chooser File chooser to display from the "..." button.
78    */

79   public DirectorySelectorComponent(Component parent, DirectoryChooser chooser) {
80     this(parent, chooser, DEFAULT_NUM_COLS, DEFAULT_FONT_SIZE);
81   }
82
83   /** Creates a new DirectorySelectorComponent whose file must exist.
84    * @param parent Parent of this component.
85    * @param chooser File chooser to display from the "..." button.
86    * @param numCols Number of columns to display in the text field
87    * @param fontSize Font size for the text field
88    */

89   public DirectorySelectorComponent(Component parent, DirectoryChooser chooser, int numCols, float fontSize) {
90     this(parent, chooser, numCols, fontSize, true);
91   }
92
93   /** Creates a new DirectorySelectorComponent.
94    * @param parent Parent of this component.
95    * @param chooser File chooser to display from the "..." button.
96    * @param numCols Number of columns to display in the text field
97    * @param fontSize Font size for the text field
98    * @param mustExist true if the file specified in the field must exist
99    */

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

161   public void setFileField(File file) {
162     _file = file;
163     if (file != null && ! file.getPath().equals("")) {
164       try { _file = file.getCanonicalFile(); }
165       catch(IOException e) { /* do nothing */ }
166     }
167     resetFileField();
168   }
169
170   public void resetFileField() {
171     if (_file == null) _fileField.setText("");
172     else {
173       _fileField.setText(_file.toString());
174       _fileField.setCaretPosition(_fileField.getText().length());
175     }
176   }
177
178   public void setToolTipText(String JavaDoc text) {
179     super.setToolTipText(text);
180     _fileField.setToolTipText(text);
181     _chooserButton.setToolTipText(text);
182   }
183
184   /** Adds a filter to decide if a directory can be chosen. */
185   public void addChoosableFileFilter(FileFilter JavaDoc filter) { _chooser.addChoosableFileFilter(filter); }
186   
187   /** Removes the given filefilter from the chooser. */
188   public void removeChoosableFileFilter(FileFilter JavaDoc filter) { _chooser.removeChoosableFileFilter(filter); }
189   
190   public void clearChoosableFileFilters() { _chooser.resetChoosableFileFilters(); }
191    
192   /** Flag indicating that validation by the focus listener or action listener is pending. The flag is used to avoid
193    * duplicating the validation process.
194    */

195   private boolean _validationInProgress = false;
196   
197   /** The chooser method for the validation of filenames that are manually entered into the text field.
198    * @return False, if file does not exist. True, otherwise.
199    */

200   public boolean validateTextField() {
201     if (_validationInProgress) return true;
202     _validationInProgress = true;
203     
204     String JavaDoc newValue = _fileField.getText().trim();
205     
206     File newFile = null;
207     if (! newValue.equals("")) {
208       newFile = new File(newValue);
209       if (! newFile.isDirectory() && _chooser.isFileSelectionEnabled()) newFile = newFile.getParentFile();
210     }
211     
212     if (newFile != null && _mustExist && ! newFile.exists()) {
213       JOptionPane.showMessageDialog(_parent, "The file '"+ newValue + "'\nis invalid because it does not exist.",
214                                     "Invalid File Name", JOptionPane.ERROR_MESSAGE);
215       resetFileField(); // revert if not valid
216
_validationInProgress = false;
217       return false;
218     }
219     else {
220       setFileField(newFile);
221       _validationInProgress = false;
222       return true;
223     }
224   }
225   
226   /** Opens the file chooser to select a file, putting the result in the file field. */
227   private void _chooseFile() {
228
229     // Get the file from the chooser
230
int returnValue = _chooser.showDialog(_file);
231     if (returnValue == DirectoryChooser.APPROVE_OPTION) {
232       File chosen = _chooser.getSelectedDirectory();
233       if (chosen != null) setFileField(chosen);
234     }
235   }
236
237 }
Popular Tags