KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > modules > form > editors2 > IconEditor


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.modules.form.editors2;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.beans.*;
25 import java.io.*;
26 import java.net.MalformedURLException JavaDoc;
27 import java.util.*;
28 import java.net.URL JavaDoc;
29
30 import javax.swing.*;
31 import javax.swing.filechooser.FileFilter JavaDoc;
32 import javax.swing.border.*;
33
34 import org.openide.*;
35 import org.openide.awt.Mnemonics;
36 import org.openide.loaders.*;
37 import org.openide.nodes.*;
38 import org.openide.explorer.ExplorerManager;
39 import org.openide.explorer.view.BeanTreeView;
40 import org.openide.explorer.propertysheet.*;
41 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
42 import org.openide.explorer.propertysheet.editors.EnhancedCustomPropertyEditor;
43 import org.openide.filesystems.FileUtil;
44 import org.openide.filesystems.FileObject;
45 import org.openide.filesystems.FileStateInvalidException;
46 import org.openide.util.NbBundle;
47
48 import org.netbeans.api.project.*;
49 import org.netbeans.api.java.classpath.ClassPath;
50 import org.netbeans.api.java.queries.SourceForBinaryQuery;
51 import org.netbeans.modules.form.FormModel;
52 import org.netbeans.modules.form.FormAwareEditor;
53 import org.netbeans.modules.form.FormDesignValue;
54 import org.netbeans.modules.form.FormEditor;
55 import org.netbeans.modules.form.FormProperty;
56 import org.netbeans.modules.form.NamedPropertyEditor;
57
58 /**
59  * PropertyEditor for Icons. Depends on existing DataObject for images.
60  * Images must be represented by some DataObject which returns itself
61  * as cookie, and has image file as a primary file. File extensions
62  * for images is specified in isImage method.
63  *
64  * @author Jan Jancura, Jan Stola
65  */

66 public class IconEditor extends PropertyEditorSupport implements
67         XMLPropertyEditor, FormAwareEditor, NamedPropertyEditor {
68     /** Type constant for icons from URL. */
69     public static final int TYPE_URL = 1;
70     /** Type constant for icons from file. */
71     public static final int TYPE_FILE = 2;
72     /** Type constant for icons from classpath. */
73     public static final int TYPE_CLASSPATH = 3;
74     /** Name prefix for icons from URL. */
75     private static final String JavaDoc URL_PREFIX = "URL"; // NOI18N
76
/** Name prefix for icons from file. */
77     private static final String JavaDoc FILE_PREFIX = "File"; // NOI18N
78
/** Name prefix for icons from file. */
79     private static final String JavaDoc CLASSPATH_PREFIX = "Classpath"; // NOI18N
80

81     /**
82      * Returns localized string from bundle.
83      *
84      * @param key key for the localized string.
85      * @return localized string for the key.
86      */

87     private static String JavaDoc getString(String JavaDoc key) {
88         return NbBundle.getBundle(IconEditor.class).getString(key);
89     }
90     
91     /**
92      * Determines whether the file contains image (it checks that it has
93      * extension that is supported).
94      *
95      * @param s name/path of the file.
96      * @return <code>true</code> if the file contains image,
97      * returns <code>false</cde> otherwise.
98      */

99     public static boolean isImage(String JavaDoc s) {
100         if (s == null) {
101             return false;
102         }
103         s = s.toLowerCase();
104         return s.endsWith(".jpg") || s.endsWith(".gif") || // NOI18N
105
s.endsWith(".jpeg") || s.endsWith(".jpe") || s.endsWith(".png"); // NOI18N
106
}
107     
108     /**
109      * Duplicates backslashes in the input string.
110      *
111      * @param s string to duplicate backslashes in.
112      * @return input string with duplicated backslashes.
113      */

114     private static String JavaDoc convert(String JavaDoc s) {
115         StringTokenizer st = new StringTokenizer(s, "\\"); // NOI18N
116
StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
117         if (st.hasMoreElements()) {
118             sb.append(st.nextElement());
119             while (st.hasMoreElements())
120                 sb.append("\\\\").append(st.nextElement()); // NOI18N
121
}
122         return sb.toString();
123     }
124     
125     // variables ..................................................................................
126

127     private FormModel formModel;
128     
129     // Special access methods......................................................................
130

131     /**
132      * Returns source type of the icon.
133      *
134      * @return the type of icon source - one of <code>TYPE_CLASSPATH</code>,
135      * <code>TYPE_FILE</code>, <code>TYPE_URL</code>.
136      */

137     public int getSourceType() {
138         if (getValue() instanceof NbImageIcon)
139             return ((NbImageIcon)getValue()).type;
140         else
141             return TYPE_FILE;
142     }
143     
144     /**
145      * Returns icon source name.
146      *
147      * @return the name of icon's source - depending on the type it can be a URL,
148      * file name or resource path to the image on classpath.
149      */

150     public String JavaDoc getSourceName() {
151         if (getValue() instanceof NbImageIcon)
152             return ((NbImageIcon)getValue()).name;
153         else
154             return null;
155     }
156     
157     // PropertyEditor methods .....................................................................
158

159     public Object JavaDoc getValue() {
160         return super.getValue();
161     }
162         
163     public String JavaDoc getAsText() {
164         Object JavaDoc val = getValue();
165         
166         if (val == null) return "null"; // NOI18N
167

168         if (val instanceof NbImageIcon) {
169             NbImageIcon ii = (NbImageIcon)val;
170             switch (ii.type) {
171                 case TYPE_URL:
172                     return URL_PREFIX + ": " + ii.name; // NOI18N
173
case TYPE_FILE:
174                     return FILE_PREFIX + ": " + ii.name; // NOI18N
175
case TYPE_CLASSPATH:
176                     return CLASSPATH_PREFIX + ": " + ii.name; // NOI18N
177
}
178         }
179         return null;
180     }
181     
182     public void setAsText(String JavaDoc string) throws IllegalArgumentException JavaDoc {
183         setValue(iconFromText(string));
184     }
185     
186     public String JavaDoc getJavaInitializationString() {
187         if (getValue() instanceof NbImageIcon) {
188             NbImageIcon ii = (NbImageIcon)getValue();
189             switch (ii.type) {
190                 case TYPE_URL: return
191                 "new javax.swing.JLabel() {\n" + // NOI18N
192
" public javax.swing.Icon getIcon() {\n" + // NOI18N
193
" try {\n" + // NOI18N
194
" return new javax.swing.ImageIcon(\n" + // NOI18N
195
" new java.net.URL(\"" + convert(ii.name) + "\")\n" + // NOI18N
196
" );\n" + // NOI18N
197
" } catch (java.net.MalformedURLException e) {\n" + // NOI18N
198
" }\n" + // NOI18N
199
" return null;\n" + // NOI18N
200
" }\n" + // NOI18N
201
"}.getIcon()"; // NOI18N
202
case TYPE_FILE: return
203                 "new javax.swing.ImageIcon(\"" + convert(ii.name) + "\")"; // NOI18N
204
case TYPE_CLASSPATH: return
205                 "new javax.swing.ImageIcon(getClass().getResource(\"" + convert(ii.name) + "\"))"; // NOI18N
206
}
207         }
208         return "null"; // NOI18N
209
}
210     
211     public String JavaDoc[] getTags() {
212         return null;
213     }
214     
215     public boolean isPaintable() {
216         return false;
217     }
218     
219     public void paintValue(Graphics g, Rectangle rectangle) {
220     }
221     
222     public boolean supportsCustomEditor() {
223         return true;
224     }
225     
226     public Component getCustomEditor() {
227         return new IconPanel();
228     }
229     
230     /**
231      * Returns URL of the given resource.
232      *
233      * @param resource name of some resource.
234      * @return URL of the given resource.
235      */

236     private URL JavaDoc findResource(String JavaDoc resource) {
237         if (resource.startsWith("/")) { // NOI18N
238
resource = resource.substring(1);
239         }
240         FileObject formFile = FormEditor.getFormDataObject(formModel).getFormFile();
241         ClassPath classPath = ClassPath.getClassPath(formFile, ClassPath.SOURCE);
242         FileObject resourceObject = classPath.findResource(resource);
243         if (resourceObject == null) {
244             classPath = ClassPath.getClassPath(formFile, ClassPath.EXECUTE);
245             resourceObject = classPath.findResource(resource);
246         }
247         if (resourceObject == null) {
248             return null;
249         } else {
250             try {
251                 return resourceObject.getURL();
252             } catch (FileStateInvalidException fsie) {
253                 ErrorManager.getDefault().notify(fsie);
254                 return null;
255             }
256         }
257     }
258     
259     public void setFormModel(FormModel model) {
260         this.formModel = model;
261     }
262     
263     /**
264      * Returns icon for the given source name.
265      *
266      * @param string source name of the icon.
267      * @return icon for the given source name.
268      * @throws IllegalArgumentException when the passed value cannot
269      * cannot be resolved to an icon.
270      */

271     private NbImageIcon iconFromText(String JavaDoc string) throws IllegalArgumentException JavaDoc {
272         NbImageIcon ii;
273         try {
274             if (string.startsWith(FILE_PREFIX)) {
275                 String JavaDoc s = string.substring(FILE_PREFIX.length() + 1).trim();
276                 ii = new NbImageIcon(s);
277                 ii.type = TYPE_FILE;
278                 ii.name = s;
279             } else
280                 if (string.startsWith(CLASSPATH_PREFIX)) {
281                     String JavaDoc s = string.substring(CLASSPATH_PREFIX.length() + 1).trim();
282                     
283                     if(("".equals(s)) || ("/".equals(s)) // NOI18N
284
|| ("///".equals(s)) || (s.endsWith("#"))) { // NOI18N
285
// #13035
286
// the empty string and couple of others has to be treated specially
287
// since TopManager.getDefault().currentClassLoader().getResource(s);
288
// is able to return non null value for the . And that
289
// wrong non-null value causes problems in new NbImageIcon(...)
290
return null;
291                     }
292                     
293                     URL JavaDoc u = findResource(s);
294                     
295                     if (u == null) {
296                         ii = new NbImageIcon();
297                     } else {
298                         ii = new NbImageIcon(u);
299                     }
300                     
301                     ii.type = TYPE_CLASSPATH;
302                     ii.name = s;
303                 } else {
304                     if (string.startsWith(URL_PREFIX)) {
305                         String JavaDoc s = string.substring(URL_PREFIX.length() + 1).trim();
306                         try {
307                             URL JavaDoc url = new URL JavaDoc(s);
308                             ii = new NbImageIcon(url);
309                         } catch (MalformedURLException JavaDoc muex) {
310                             ii = new NbImageIcon();
311                         }
312                         ii.type = TYPE_URL;
313                         ii.name = s;
314                     } else {
315                         if (string.equals("null")) { // NOI18N
316
ii = null;
317                         } else {
318                             ii = new NbImageIcon(string.trim());
319                             ii.type = TYPE_FILE;
320                             ii.name = string;
321                         }
322                     }
323                 }
324         } catch (Exception JavaDoc e) {
325             IllegalArgumentException JavaDoc iae = new IllegalArgumentException JavaDoc();
326             throw iae;
327         }
328         return ii;
329     }
330     
331     // NamedPropertyEditor implementation
332
public String JavaDoc getDisplayName() {
333         return NbBundle.getBundle(getClass()).getString("CTL_IconEditor_DisplayName"); // NOI18N
334
}
335     
336     // innerclasses ...............................................................................
337

338     public static class NbImageIcon implements FormDesignValue, Serializable {
339         /** generated Serialized Version UID */
340         static final long serialVersionUID = 7018807466471349466L;
341         /** The icon itself. */
342         private ImageIcon icon = new ImageIcon("");
343         /** Source type of the icon. */
344         private int type;
345         /** Name of the icon. */
346         private String JavaDoc name;
347         
348         public NbImageIcon() {
349         }
350         
351         NbImageIcon(URL JavaDoc url) {
352             type = TYPE_URL;
353             try {
354                 icon = new ImageIcon(url);
355             } catch (Exception JavaDoc ex) {}
356         }
357         
358         NbImageIcon(String JavaDoc file) {
359             type = TYPE_FILE;
360             try {
361                 icon = new ImageIcon(file);
362             } catch (Exception JavaDoc ex) {}
363         }
364         
365         public NbImageIcon(NbImageIcon nbIcon) {
366             icon = nbIcon.icon;
367             type = nbIcon.type;
368             name = nbIcon.name;
369         }
370         
371         String JavaDoc getName() {
372             return name;
373         }
374         
375         public Object JavaDoc getDesignValue() {
376             return icon;
377         }
378         
379         public String JavaDoc getDescription() {
380             return name;
381         }
382         
383         public FormDesignValue copy(FormProperty formProperty) {
384             return new IconEditor.NbImageIcon(this);
385         }
386     }
387     
388     
389     private class IconPanel extends JPanel implements EnhancedCustomPropertyEditor, ActionListener {
390         /** generated Serialized Version UID */
391         static final long serialVersionUID = -6904264999063788703L;
392         
393         private JPanel jPanel1;
394         private JLabel jLabel1;
395         private JRadioButton rbUrl;
396         private JRadioButton rbFile;
397         private JRadioButton rbClasspath;
398         private JRadioButton rbNoPicture;
399         private JLabel jLabel2;
400         private JLabel jLabel3;
401         private JLabel jLabel4;
402         private JLabel jLabel5;
403         private JPanel jPanel2;
404         private JLabel lName;
405         private JTextField tfName;
406         private JButton bSelect;
407         private JPanel jPanel3;
408         private JLabel jLabel7;
409         private JScrollPane spImage;
410         private JLabel iconLabel;
411         
412         // ======================================
413

414         private NbImageIcon localIcon;
415         
416         /**
417          * Creates new form <code>IconPanel</code>.
418          */

419         public IconPanel() {
420             iconLabel = new JLabel() {
421                 public boolean isFocusTraversable() {
422                     return true;
423                 }
424             };
425             iconLabel.setPreferredSize(new Dimension(32, 32));
426             iconLabel.setHorizontalAlignment(SwingConstants.CENTER);
427             iconLabel.setVerticalAlignment(SwingConstants.CENTER);
428             
429             initComponents();
430             spImage.setViewportView(iconLabel);
431             
432             jLabel1.setText(getString("CTL_ImageSourceType")); // NOI18N
433
jLabel2.setText(getString("CTL_URLExample")); // NOI18N
434
jLabel3.setText(getString("CTL_FileExample")); // NOI18N
435
jLabel4.setText(getString("CTL_ClasspathExample")); // NOI18N
436
jLabel5.setText(getString("CTL_Null")); // NOI18N
437
lName.setLabelFor(tfName);
438             
439             jLabel1.setLabelFor(jPanel1);
440             jLabel2.setLabelFor(rbUrl);
441             jLabel3.setLabelFor(rbFile);
442             jLabel4.setLabelFor(rbClasspath);
443             jLabel5.setLabelFor(rbNoPicture);
444             jLabel7.setLabelFor(iconLabel);
445
446             Mnemonics.setLocalizedText(rbUrl, getString("CTL_URL")); // NOI18N
447
Mnemonics.setLocalizedText(rbFile, getString("CTL_File")); // NOI18N
448
Mnemonics.setLocalizedText(rbClasspath, getString("CTL_Classpath")); // NOI18N
449
Mnemonics.setLocalizedText(rbNoPicture, getString("CTL_NoPicture")); // NOI18N
450
Mnemonics.setLocalizedText(lName, getString("CTL_ImageSourceName")); // NOI18N
451
Mnemonics.setLocalizedText(jLabel7, getString("CTL_Preview")); // NOI18N
452
Mnemonics.setLocalizedText(bSelect, getString("CTL_ButtonSelect")); // NOI18N
453

454             tfName.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_ImageSourceName")); // NOI18N
455
bSelect.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_ButtonSelect")); // NOI18N
456
iconLabel.getAccessibleContext().setAccessibleDescription(getString("ACSD_CTL_Preview")); // NOI18N
457
rbUrl.getAccessibleContext().setAccessibleDescription(jLabel2.getText());
458             rbFile.getAccessibleContext().setAccessibleDescription(jLabel3.getText());
459             rbClasspath.getAccessibleContext().setAccessibleDescription(jLabel4.getText());
460             rbNoPicture.getAccessibleContext().setAccessibleDescription(jLabel5.getText());
461             
462             getAccessibleContext().setAccessibleDescription(getString("ACSD_IconCustomEditor")); // NOI18N
463

464             ButtonGroup bg = new ButtonGroup();
465             bg.add(rbUrl);
466             bg.add(rbFile);
467             bg.add(rbClasspath);
468             bg.add(rbNoPicture);
469             
470             Object JavaDoc value = getValue();
471             
472             if (!(value instanceof NbImageIcon)) {
473                 rbNoPicture.setSelected(true);
474                 bSelect.setEnabled(false);
475                 tfName.setEnabled(false);
476                 return;
477             } else {
478                 localIcon = (NbImageIcon)value;
479             }
480             
481             switch (((NbImageIcon)localIcon).type) {
482                 case TYPE_URL:
483                     rbUrl.setSelected(true);
484                     bSelect.setEnabled(false);
485                     break;
486                 case TYPE_FILE:
487                     rbFile.setSelected(true);
488                     bSelect.setEnabled(true);
489                     break;
490                 case TYPE_CLASSPATH:
491                     rbClasspath.setSelected(true);
492                     bSelect.setEnabled(true);
493                     break;
494             }
495             tfName.setText(((NbImageIcon)localIcon).name);
496             
497             updateIcon();
498         }
499         
500         /**
501          * This method is called from within the constructor to initialize the form.
502          */

503         private void initComponents() {
504             jPanel1 = new JPanel();
505             jLabel1 = new JLabel();
506             rbUrl = new JRadioButton();
507             rbFile = new JRadioButton();
508             rbClasspath = new JRadioButton();
509             rbNoPicture = new JRadioButton();
510             jLabel2 = new JLabel();
511             jLabel3 = new JLabel();
512             jLabel4 = new JLabel();
513             jLabel5 = new JLabel();
514             jPanel2 = new JPanel();
515             lName = new JLabel();
516             tfName = new JTextField();
517             bSelect = new JButton();
518             jPanel3 = new JPanel();
519             jLabel7 = new JLabel();
520             spImage = new JScrollPane();
521             
522             setLayout(new GridBagLayout());
523             GridBagConstraints gridBagConstraints2;
524             
525             jPanel1.setLayout(new GridBagLayout());
526             GridBagConstraints gridBagConstraints1;
527             
528             gridBagConstraints1 = new GridBagConstraints();
529             gridBagConstraints1.insets = new Insets(12, 12, 0, 0);
530             gridBagConstraints1.anchor = GridBagConstraints.WEST;
531             jPanel1.add(jLabel1, gridBagConstraints1);
532             
533             gridBagConstraints1 = new GridBagConstraints();
534             gridBagConstraints1.gridx = 0;
535             gridBagConstraints1.gridy = 1;
536             gridBagConstraints1.insets = new Insets(12, 24, 0, 0);
537             gridBagConstraints1.anchor = GridBagConstraints.WEST;
538             jPanel1.add(rbUrl, gridBagConstraints1);
539             
540             gridBagConstraints1 = new GridBagConstraints();
541             gridBagConstraints1.gridx = 0;
542             gridBagConstraints1.gridy = 2;
543             gridBagConstraints1.insets = new Insets(0, 24, 0, 0);
544             gridBagConstraints1.anchor = GridBagConstraints.WEST;
545             jPanel1.add(rbFile, gridBagConstraints1);
546             
547             gridBagConstraints1 = new GridBagConstraints();
548             gridBagConstraints1.gridx = 0;
549             gridBagConstraints1.gridy = 3;
550             gridBagConstraints1.insets = new Insets(0, 24, 0, 0);
551             gridBagConstraints1.anchor = GridBagConstraints.WEST;
552             jPanel1.add(rbClasspath, gridBagConstraints1);
553             
554             gridBagConstraints1 = new GridBagConstraints();
555             gridBagConstraints1.gridx = 0;
556             gridBagConstraints1.gridy = 4;
557             gridBagConstraints1.insets = new Insets(0, 24, 0, 0);
558             gridBagConstraints1.anchor = GridBagConstraints.WEST;
559             jPanel1.add(rbNoPicture, gridBagConstraints1);
560             
561             gridBagConstraints1 = new GridBagConstraints();
562             gridBagConstraints1.gridx = 1;
563             gridBagConstraints1.gridy = 1;
564             gridBagConstraints1.insets = new Insets(12, 5, 0, 12);
565             gridBagConstraints1.anchor = GridBagConstraints.WEST;
566             jPanel1.add(jLabel2, gridBagConstraints1);
567             
568             gridBagConstraints1 = new GridBagConstraints();
569             gridBagConstraints1.gridx = 1;
570             gridBagConstraints1.gridy = 2;
571             gridBagConstraints1.insets = new Insets(5, 5, 0, 12);
572             gridBagConstraints1.anchor = GridBagConstraints.WEST;
573             jPanel1.add(jLabel3, gridBagConstraints1);
574             
575             gridBagConstraints1 = new GridBagConstraints();
576             gridBagConstraints1.gridx = 1;
577             gridBagConstraints1.gridy = 3;
578             gridBagConstraints1.insets = new Insets(5, 5, 0, 12);
579             gridBagConstraints1.anchor = GridBagConstraints.WEST;
580             jPanel1.add(jLabel4, gridBagConstraints1);
581             
582             gridBagConstraints1 = new GridBagConstraints();
583             gridBagConstraints1.gridx = 1;
584             gridBagConstraints1.gridy = 4;
585             gridBagConstraints1.insets = new Insets(5, 5, 0, 12);
586             gridBagConstraints1.anchor = GridBagConstraints.WEST;
587             gridBagConstraints1.weightx = 1.0;
588             gridBagConstraints1.weighty = 1.0;
589             jPanel1.add(jLabel5, gridBagConstraints1);
590             
591             gridBagConstraints2 = new GridBagConstraints();
592             gridBagConstraints2.fill = GridBagConstraints.BOTH;
593             add(jPanel1, gridBagConstraints2);
594             
595             jPanel2.setLayout(new GridBagLayout());
596             GridBagConstraints gridBagConstraints3;
597             
598             gridBagConstraints3 = new GridBagConstraints();
599             gridBagConstraints3.insets = new Insets(12, 12, 0, 0);
600             gridBagConstraints3.anchor = GridBagConstraints.WEST;
601             jPanel2.add(lName, gridBagConstraints3);
602             
603             gridBagConstraints3 = new GridBagConstraints();
604             gridBagConstraints3.fill = GridBagConstraints.HORIZONTAL;
605             gridBagConstraints3.insets = new Insets(12, 5, 0, 0);
606             gridBagConstraints3.anchor = GridBagConstraints.WEST;
607             gridBagConstraints3.weightx = 1.0;
608             jPanel2.add(tfName, gridBagConstraints3);
609             
610             gridBagConstraints3 = new GridBagConstraints();
611             gridBagConstraints3.insets = new Insets(12, 5, 0, 17);
612             gridBagConstraints3.anchor = GridBagConstraints.WEST;
613             jPanel2.add(bSelect, gridBagConstraints3);
614             
615             gridBagConstraints2 = new GridBagConstraints();
616             gridBagConstraints2.gridx = 0;
617             gridBagConstraints2.gridy = 1;
618             gridBagConstraints2.fill = GridBagConstraints.BOTH;
619             add(jPanel2, gridBagConstraints2);
620             
621             jPanel3.setLayout(new GridBagLayout());
622             GridBagConstraints gridBagConstraints4;
623             
624             gridBagConstraints4 = new GridBagConstraints();
625             gridBagConstraints4.insets = new Insets(12, 12, 0, 0);
626             gridBagConstraints4.anchor = GridBagConstraints.WEST;
627             jPanel3.add(jLabel7, gridBagConstraints4);
628             
629             gridBagConstraints4 = new GridBagConstraints();
630             gridBagConstraints4.gridx = 0;
631             gridBagConstraints4.gridy = 1;
632             gridBagConstraints4.fill = GridBagConstraints.BOTH;
633             gridBagConstraints4.insets = new Insets(5, 12, 0, 12);
634             gridBagConstraints4.weightx = 1.0;
635             gridBagConstraints4.weighty = 1.0;
636             jPanel3.add(spImage, gridBagConstraints4);
637             
638             gridBagConstraints2 = new GridBagConstraints();
639             gridBagConstraints2.gridx = 0;
640             gridBagConstraints2.gridy = 2;
641             gridBagConstraints2.fill = GridBagConstraints.BOTH;
642             gridBagConstraints2.weightx = 1.0;
643             gridBagConstraints2.weighty = 1.0;
644             add(jPanel3, gridBagConstraints2);
645             
646             // listeners .................................................
647

648             tfName.addActionListener(this);
649             rbFile.addActionListener(this);
650             rbUrl.addActionListener(this);
651             rbClasspath.addActionListener(this);
652             rbNoPicture.addActionListener(this);
653             bSelect.addActionListener(this);
654         }
655         
656         public void actionPerformed(ActionEvent e) {
657             Object JavaDoc source = e.getSource();
658             if (source == tfName) {
659                 setValue();
660             } else if (source == rbFile) {
661                 bSelect.setEnabled(true);
662                 tfName.setEnabled(true);
663                 setValue();
664                 updateIcon();
665             } else if (source == rbUrl) {
666                 bSelect.setEnabled(false);
667                 tfName.setEnabled(true);
668                 setValue();
669             } else if (source == rbClasspath) {
670                 bSelect.setEnabled(true);
671                 tfName.setEnabled(true);
672                 setValue();
673             } else if (source == rbNoPicture) {
674                 bSelect.setEnabled(false);
675                 tfName.setEnabled(false);
676                 localIcon = null;
677                 updateIcon();
678             } else if (source == bSelect) {
679                 if(rbFile.isSelected()) {
680                     File f = selectFile();
681                     if (f != null) {
682                         tfName.setText(f.getAbsolutePath());
683                         setValue();
684                     }
685                 } else {
686                     if (rbClasspath.isSelected()) {
687                         String JavaDoc name = selectResource();
688                         if (name != null) {
689                             tfName.setText("/" + name); // NOI18N
690
setValue();
691                         }
692                     }
693                 }
694                 
695             }
696         }
697         
698         
699         /**
700          * Presents the user with the file chooser type dialog.
701          *
702          * @returns the file selected or <code>null</code>.
703          */

704         private File selectFile() {
705             final File[] ff = new File[1];
706             final FeatureDescriptor fd = new FeatureDescriptor();
707             ExPropertyModel epm = new ExPropertyModel() {
708                 public void setValue(Object JavaDoc val) {
709                     ff[0] = (File)val;
710                 }
711                 public Object JavaDoc getValue() {
712                     return ff[0];
713                 }
714                 public Class JavaDoc getPropertyType() {
715                     return File.class;
716                 }
717                 public Class JavaDoc getPropertyEditorClass() {
718                     return null;
719                 }
720                 public void addPropertyChangeListener(PropertyChangeListener l) {
721                 }
722                 public void removePropertyChangeListener(PropertyChangeListener l) {
723                 }
724                 public Object JavaDoc[] getBeans() {
725                     return new Object JavaDoc[0];
726                 }
727                 public FeatureDescriptor getFeatureDescriptor() {
728                     return fd;
729                 }
730             };
731             FileFilter JavaDoc filter = new FileFilter JavaDoc() {
732                 public boolean accept(java.io.File JavaDoc f) {
733                     return isImage(f.getName()) || f.isDirectory();
734                 }
735                 public String JavaDoc getDescription() {
736                     return getString("CTL_ImagesExtensionName"); // NOI18N
737
}
738             };
739             fd.setValue("directories", Boolean.FALSE); // NOI18N
740
fd.setValue("files", Boolean.TRUE); // NOI18N
741
fd.setValue("filter", filter); // NOI18N
742
PropertyPanel panel = new PropertyPanel(epm, PropertyPanel.PREF_CUSTOM_EDITOR);
743             DialogDescriptor dd = new DialogDescriptor(panel, getString("CTL_OpenDialogName"), true, null); // NOI18N
744
Object JavaDoc res = DialogDisplayer.getDefault().notify(dd);
745             if (res == DialogDescriptor.OK_OPTION) {
746                 return ff[0];
747             } else {
748                 return null;
749             }
750         }
751         
752         private java.util.List JavaDoc getRoots(ClassPath cp) {
753             ArrayList l = new ArrayList(cp.entries().size());
754             Iterator eit = cp.entries().iterator();
755             while(eit.hasNext()) {
756                 ClassPath.Entry e = (ClassPath.Entry)eit.next();
757                 
758                 // try to map it to sources
759
URL JavaDoc url = e.getURL();
760                 SourceForBinaryQuery.Result r= SourceForBinaryQuery.findSourceRoots(url);
761                 FileObject [] fos = r.getRoots();
762                 if (fos.length > 0) {
763                     for (int i = 0 ; i < fos.length; i++) l.add(fos[i]);
764                 } else {
765                     if (e.getRoot()!=null)
766                         l.add(e.getRoot()); // add the class-path location
767
// directly
768
}
769             }
770             
771             return l;
772         }
773         
774         /**
775          * Obtains icon resource from the user.
776          *
777          * @returns name of the selected resource or <code>null</code>.
778          */

779         private String JavaDoc selectResource() {
780             FileObject formFile = FormEditor.getFormDataObject(formModel).getFormFile();
781             ClassPath executeClassPath = ClassPath.getClassPath(formFile, ClassPath.EXECUTE);
782             java.util.List JavaDoc roots = (executeClassPath == null) ? Collections.EMPTY_LIST : getRoots(executeClassPath);
783             Project project = FileOwnerQuery.getOwner(formFile);
784             Node nodes[] = new Node[roots.size()];
785             int selRoot = -1;
786             try {
787                 ListIterator iter = roots.listIterator();
788                 while (iter.hasNext()) {
789                     FileObject root = (FileObject)iter.next();
790                     DataObject dob = DataObject.find(root);
791                     Project owner = FileOwnerQuery.getOwner(root);
792                     final String JavaDoc displayName = rootDisplayName(root, owner, owner != project);
793                     nodes[iter.previousIndex()] = new RootNode(dob.getNodeDelegate(), displayName);
794                 }
795             } catch (DataObjectNotFoundException donfex) {
796                 ErrorManager.getDefault().notify(ErrorManager.EXCEPTION, donfex);
797                 return null;
798             }
799             Children children = new Children.Array();
800             children.add(nodes);
801             final AbstractNode root = new AbstractNode(children);
802             root.setIconBase("org/netbeans/modules/form/editors2/iconResourceRoot"); // NOI18N
803
root.setDisplayName(getString("CTL_ClassPathName")); // NOI18N
804

805             ResourceSelector selector = new ResourceSelector(root);
806             DialogDescriptor dd = new DialogDescriptor(selector, getString("CTL_OpenDialogName")); // NOI18N
807
Object JavaDoc res = DialogDisplayer.getDefault().notify(dd);
808             nodes = (res == DialogDescriptor.OK_OPTION) ? selector.getNodes() : null;
809             String JavaDoc name = null;
810             if ((nodes != null) && (nodes.length == 1)) {
811                 DataObject dob = (DataObject)nodes[0].getCookie(DataObject.class);
812                 if (dob != null) {
813                     FileObject fob = dob.getPrimaryFile();
814                     if (fob != null) {
815                         if (executeClassPath.contains(fob)) {
816                             name = executeClassPath.getResourceName(fob);
817                         } else {
818                             ClassPath sourceClassPath = ClassPath.getClassPath(fob, ClassPath.SOURCE);
819                             name = sourceClassPath.getResourceName(fob);
820                         }
821                     }
822                 }
823             }
824             return name;
825         }
826         
827         private String JavaDoc rootDisplayName(FileObject fo, Project owner, boolean withProjectName) {
828             if (owner != null) {
829                 SourceGroup grp = sourceGroup(fo, owner);
830                 String JavaDoc name = (grp!=null) ? grp.getDisplayName() : FileUtil.getFileDisplayName(fo);
831                 if (withProjectName) {
832                     ProjectInformation pi = ProjectUtils.getInformation(owner);
833                     name += " [" + pi.getDisplayName() + "]"; // NOI18N
834
}
835                 return name;
836             } else
837                 return FileUtil.getFileDisplayName(fo);
838         }
839         
840         private SourceGroup sourceGroup(FileObject file, Project prj) {
841             Sources src = ProjectUtils.getSources(prj);
842             SourceGroup[] srcgrps = src.getSourceGroups("java"); // NOI18N
843
for (int i = 0 ; i < srcgrps.length; i++) {
844                 if (file == srcgrps[i].getRootFolder())
845                     return srcgrps[i];
846             }
847             return null;
848         }
849         
850         /*private Node findSelectedNode(Node root, String name) {
851             Node node = root;
852             StringTokenizer st = new StringTokenizer(name, "/"); // NOI18N
853             while (st.hasMoreTokens()) {
854                 Children children = node.getChildren();
855                 String subName = st.nextToken();
856                 Node nextNode = children.findChild(subName);
857                 // Last component => try to remove prefix
858                 if ((nextNode == null) && !st.hasMoreTokens()) {
859                     int index = subName.lastIndexOf('.');
860                     if (index != -1) {
861                         subName = subName.substring(0, index);
862                         nextNode = children.findChild(subName);
863                     }
864                 }
865                 if (nextNode == null) {
866                     break;
867                 } else {
868                     node = nextNode;
869                 }
870             }
871             return node;
872         }*/

873         
874         /**
875          * Returns the property value that is result of the CustomPropertyEditor.
876          *
877          * @return the property value that is result of the CustomPropertyEditor.
878          * @exception InvalidStateException when the custom property editor does not
879          * represent valid property value (and thus it should not be set)
880          */

881         public Object JavaDoc getPropertyValue() throws IllegalStateException JavaDoc {
882             NbImageIcon ii = null;
883             String JavaDoc s = tfName.getText().trim();
884             
885             if (("".equals(s)) || ("/".equals(s)) || // NOI18N
886
("///".equals(s)) || (s.endsWith("#"))) { // NOI18N
887
// #13035
888
// the empty string and couple of others has to be treated specially
889
// since TopManager.getDefault().currentClassLoader().getResource(s);
890
// is able to return non null value for the . And that
891
// wrong non-null value causes problems in new NbImageIcon(...)
892
return null;
893             }
894             
895             if (rbFile.isSelected()) {
896                 ii = new NbImageIcon(s);
897                 ii.type = TYPE_FILE;
898                 ii.name = s;
899             } else if (rbClasspath.isSelected()) {
900                 URL JavaDoc url = findResource(s);
901                 ii = new NbImageIcon(url);
902                 ii.type = TYPE_CLASSPATH;
903                 ii.name = s;
904             } else if (rbUrl.isSelected()) {
905                 URL JavaDoc url = null;
906                 try {
907                     url = new URL JavaDoc(s);
908                 } catch (MalformedURLException JavaDoc ex) {}
909                 ii = new NbImageIcon(url);
910                 ii.type = TYPE_URL;
911                 ii.name = s;
912             }
913             return ii;
914         }
915         
916         void updateIcon() {
917             IconEditor.this.setValue(localIcon);
918             iconLabel.setIcon((localIcon == null) ? null : localIcon.icon);
919             iconLabel.setEnabled(localIcon != null);
920             validate();
921         }
922         
923         void setValue() {
924             String JavaDoc val = tfName.getText();
925             if ("".equals(val)) { // NOI18N
926
localIcon = null;
927                 updateIcon();
928                 return;
929             }
930             
931             String JavaDoc pref = ""; // NOI18N
932
if (rbUrl.isSelected()) pref = URL_PREFIX + ": "; // NOI18N
933
else
934                 if (rbFile.isSelected()) pref = FILE_PREFIX + ": "; // NOI18N
935
else
936                     if (rbClasspath.isSelected()) pref = CLASSPATH_PREFIX + ": "; // NOI18N
937
try {
938                 localIcon = iconFromText(pref + val);
939             } catch (IllegalArgumentException JavaDoc ee) {
940                 localIcon = null;
941             }
942             updateIcon();
943         }
944         
945     } // end of IconPanel
946

947     private static class RootNode extends FilterNode {
948         
949         RootNode(Node node, String JavaDoc displayName) {
950             super(node);
951             if (displayName != null) {
952                 disableDelegation(DELEGATE_GET_DISPLAY_NAME | DELEGATE_SET_DISPLAY_NAME);
953                 setDisplayName(displayName);
954             }
955         }
956                 
957     }
958     
959     private static class ResourceSelector extends JPanel implements ExplorerManager.Provider {
960         /** Manages the tree. */
961         private ExplorerManager manager = new ExplorerManager();
962                 
963         public ResourceSelector(Node root) {
964             ResourceBundle bundle = NbBundle.getBundle(ResourceSelector.class);
965             
966             setLayout(new BorderLayout(0, 5));
967             setBorder(new EmptyBorder(12, 12, 0, 11));
968             getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_ResourceSelector")); // NOI18N
969
getAccessibleContext().setAccessibleName(bundle.getString("ACSN_ResourceSelector")); // NOI18N
970
manager.setRootContext(root);
971             
972             BeanTreeView tree = new BeanTreeView();
973             tree.setPopupAllowed(false);
974             tree.setDefaultActionAllowed(false);
975             // install proper border for tree
976
tree.setBorder((Border)UIManager.get("Nb.ScrollPane.border")); // NOI18N
977
tree.getAccessibleContext().setAccessibleName(bundle.getString("ACSN_ResourceSelectorView")); // NOI18N
978
tree.getAccessibleContext().setAccessibleDescription(bundle.getString("ACSD_ResourceSelectorView")); // NOI18N
979
add(tree, BorderLayout.CENTER);
980         }
981         
982         /**
983          * Gets preferred size. Overrides superclass method.
984          * Height is adjusted to 1/2 screen.
985          */

986         public Dimension getPreferredSize() {
987             Dimension dim = super.getPreferredSize();
988             dim.height = Math.max(dim.height, org.openide.util.Utilities.getUsableScreenBounds().height / 2);
989             return dim;
990         }
991         
992         /**
993          * @return selected nodes
994          */

995         public Node[] getNodes() {
996             return manager.getSelectedNodes();
997         }
998         
999         public ExplorerManager getExplorerManager() {
1000            return manager;
1001        }
1002        
1003    }
1004        
1005    // XMLPropertyEditor implementation ...........................................................
1006

1007    /** Root of the XML representation of the icon. */
1008    public static final String JavaDoc XML_IMAGE = "Image"; // NOI18N
1009

1010    /** Attribute holding icon type. */
1011    public static final String JavaDoc ATTR_TYPE = "iconType"; // NOI18N
1012
/** Attribute holding icon name. */
1013    public static final String JavaDoc ATTR_NAME = "name"; // NOI18N
1014

1015    public void readFromXML(org.w3c.dom.Node JavaDoc element) throws java.io.IOException JavaDoc {
1016        if (!XML_IMAGE.equals(element.getNodeName())) {
1017            throw new java.io.IOException JavaDoc();
1018        }
1019        org.w3c.dom.NamedNodeMap JavaDoc attributes = element.getAttributes();
1020        try {
1021            int type = Integer.parseInt(attributes.getNamedItem(ATTR_TYPE).getNodeValue());
1022            String JavaDoc name = attributes.getNamedItem(ATTR_NAME).getNodeValue();
1023            switch (type) {
1024                case 0: setValue(null); break;
1025                case TYPE_URL: setAsText(URL_PREFIX + ": " + name); break; // NOI18N
1026
case TYPE_FILE: setAsText(FILE_PREFIX + ": " + name); break; // NOI18N
1027
case TYPE_CLASSPATH: setAsText(CLASSPATH_PREFIX + ": " + name); break; // NOI18N
1028
}
1029        } catch (NullPointerException JavaDoc e) {
1030            java.io.IOException JavaDoc ioe = new java.io.IOException JavaDoc();
1031            ErrorManager.getDefault().annotate(ioe, e);
1032            throw ioe;
1033        }
1034    }
1035    
1036    public org.w3c.dom.Node JavaDoc storeToXML(org.w3c.dom.Document JavaDoc doc) {
1037        org.w3c.dom.Element JavaDoc el = doc.createElement(XML_IMAGE);
1038        if (getValue() instanceof NbImageIcon) {
1039            NbImageIcon ii = (NbImageIcon)getValue();
1040            el.setAttribute(ATTR_TYPE, Integer.toString(ii.type));
1041            el.setAttribute(ATTR_NAME, ii.name);
1042        } else {
1043            el.setAttribute(ATTR_TYPE, "0"); // NOI18N
1044
el.setAttribute(ATTR_NAME, "null"); // NOI18N
1045
}
1046        return el;
1047    }
1048    
1049}
1050
Popular Tags