KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > beaninfo > editors > ColorEditor


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
21 package org.netbeans.beaninfo.editors;
22
23
24 import java.awt.BorderLayout JavaDoc;
25 import java.awt.Color JavaDoc;
26 import java.awt.Component JavaDoc;
27 import java.awt.Dimension JavaDoc;
28 import java.awt.Graphics JavaDoc;
29 import java.awt.FontMetrics JavaDoc;
30 import java.awt.Graphics2D JavaDoc;
31 import java.awt.Rectangle JavaDoc;
32 import java.awt.RenderingHints JavaDoc;
33 import java.awt.SystemColor JavaDoc;
34 import java.awt.Toolkit JavaDoc;
35 import java.beans.PropertyChangeEvent JavaDoc;
36 import java.beans.PropertyChangeListener JavaDoc;
37 import java.beans.PropertyChangeSupport JavaDoc;
38 import java.beans.PropertyEditor JavaDoc;
39 import java.text.MessageFormat JavaDoc;
40 import java.util.Enumeration JavaDoc;
41 import java.util.HashMap JavaDoc;
42 import java.util.Map JavaDoc;
43 import javax.swing.border.EmptyBorder JavaDoc;
44 import javax.swing.colorchooser.AbstractColorChooserPanel JavaDoc;
45 import javax.swing.colorchooser.ColorSelectionModel JavaDoc;
46 import javax.swing.colorchooser.DefaultColorSelectionModel JavaDoc;
47 import javax.swing.event.*;
48 import javax.swing.Icon JavaDoc;
49 import javax.swing.JColorChooser JavaDoc;
50 import javax.swing.JList JavaDoc;
51 import javax.swing.JPanel JavaDoc;
52 import javax.swing.JScrollPane JavaDoc;
53 import javax.swing.ListCellRenderer JavaDoc;
54 import javax.swing.UIDefaults JavaDoc;
55 import javax.swing.UIManager JavaDoc;
56 import org.netbeans.core.UIExceptions;
57 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
58 import org.openide.util.NbBundle;
59
60
61 /** A property editor for Color class.
62  * (Final only for performance, can be unfinaled if desired).
63  *
64  * @author Jan Jancura, Ian Formanek
65  */

66 public final class ColorEditor implements PropertyEditor JavaDoc, XMLPropertyEditor {
67     
68     // static .....................................................................................
69

70     /** AWT Palette mode. */
71     public static final int AWT_PALETTE = 1;
72     /** System Palette mode. */
73     public static final int SYSTEM_PALETTE = 2;
74     /** Swing Palette mode. */
75     public static final int SWING_PALETTE = 3;
76
77     /** Localized names of AWT colors. */
78     private static String JavaDoc awtColorNames[];
79
80     /** AWT colors used in AWT Palette. */
81     private static final Color JavaDoc awtColors[] = {
82         Color.white, Color.lightGray, Color.gray, Color.darkGray,
83         Color.black, Color.red, Color.pink, Color.orange, Color.yellow,
84         Color.green, Color.magenta, Color.cyan, Color.blue };
85
86     /** Names of system colors. <em>Note:</em> not localizable,
87      * those names corresponds to programatical names. */

88     private static final String JavaDoc awtGenerate[] = {
89         "white", "lightGray", "gray", "darkGray", // NOI18N
90
"black", "red", "pink", "orange", "yellow", // NOI18N
91
"green", "magenta", "cyan", "blue" }; // NOI18N
92

93     /** Localized names of system colors. */
94     private static String JavaDoc systemColorNames[];
95
96     /** Names of system colors. <em>Note:</em> not localizable,
97      * those names corresponds to programatical names. */

98     private static final String JavaDoc systemGenerate[] = {
99         "activeCaption", "activeCaptionBorder", // NOI18N
100
"activeCaptionText", "control", "controlDkShadow", // NOI18N
101
"controlHighlight", "controlLtHighlight", // NOI18N
102
"controlShadow", "controlText", "desktop", // NOI18N
103
"inactiveCaption", "inactiveCaptionBorder", // NOI18N
104
"inactiveCaptionText", "info", "infoText", "menu", // NOI18N
105
"menuText", "scrollbar", "text", "textHighlight", // NOI18N
106
"textHighlightText", "textInactiveText", "textText", // NOI18N
107
"window", "windowBorder", "windowText"}; // NOI18N
108

109     /** System colors used in System Palette. */
110     private static final Color JavaDoc systemColors[] = {
111         SystemColor.activeCaption, SystemColor.activeCaptionBorder,
112         SystemColor.activeCaptionText, SystemColor.control,
113         SystemColor.controlDkShadow, SystemColor.controlHighlight,
114         SystemColor.controlLtHighlight, SystemColor.controlShadow,
115         SystemColor.controlText, SystemColor.desktop,
116         SystemColor.inactiveCaption, SystemColor.inactiveCaptionBorder,
117         SystemColor.inactiveCaptionText, SystemColor.info,
118         SystemColor.infoText, SystemColor.menu,
119         SystemColor.menuText, SystemColor.scrollbar, SystemColor.text,
120         SystemColor.textHighlight, SystemColor.textHighlightText,
121         SystemColor.textInactiveText, SystemColor.textText,
122         SystemColor.window, SystemColor.windowBorder,
123         SystemColor.windowText};
124
125     /** Swing colors names and values are static and lazy initialized.
126      * They are also cleared when l&f changes. */

127     private static String JavaDoc swingColorNames[];
128     
129     /** Swing colors used in Swing Palette. */
130     private static Color JavaDoc swingColors[];
131
132     static final boolean GTK = "GTK".equals(UIManager.getLookAndFeel().getID());//NOI18N
133
static final boolean AQUA = "Aqua".equals(UIManager.getLookAndFeel().getID());//NOI18N
134

135     private static final boolean antialias = Boolean.getBoolean("nb.cellrenderer.antialiasing") // NOI18N
136
||Boolean.getBoolean("swing.aatext") // NOI18N
137
||(GTK && gtkShouldAntialias()) // NOI18N
138
||AQUA;
139
140     private static Boolean JavaDoc gtkAA;
141     private static Map JavaDoc hintsMap;
142     
143     
144     // static initializer .........................................
145

146     static {
147         UIManager.addPropertyChangeListener(new PropertyChangeListener JavaDoc() {
148             public void propertyChange(PropertyChangeEvent JavaDoc evt) {
149                 swingColorNames = null;
150                 swingColors = null;
151             }
152         });
153         
154         swingColorNames = null;
155         swingColors = null;
156     }
157
158     // variables ..................................................................................
159

160     /** Selected color. */
161     private SuperColor superColor;
162     /** Property change support. Helper field. */
163     private PropertyChangeSupport JavaDoc support;
164
165
166     /** Gets <code>staticChooser</code> instance. */
167     public static JColorChooser JavaDoc getStaticChooser(ColorEditor ce) {
168         JColorChooser JavaDoc staticChooser = new JColorChooser JavaDoc (new DefaultColorSelectionModel JavaDoc(Color.white)
169                                                 {
170                                                     public void setSelectedColor(Color JavaDoc color) {
171                                                         if (color instanceof SuperColor) {
172                                                             super.setSelectedColor((SuperColor) color);
173                                                         }
174                                                         else if (color instanceof Color JavaDoc) {
175                                                             super.setSelectedColor(new SuperColor(color));
176                                                         }
177                                                     }
178                                                 } )
179                             {
180                                 public void setColor (Color JavaDoc c) {
181                                     if (c == null) return;
182                                     super.setColor (c);
183                                 }
184                             };
185             staticChooser.addChooserPanel (
186                 new NbColorChooserPanel (AWT_PALETTE, getAWTColorNames(), awtColors,
187                                          getString ("CTL_AWTPalette"), ce)
188             );
189             initSwingConstants();
190             staticChooser.addChooserPanel (
191                 new NbColorChooserPanel (SWING_PALETTE, swingColorNames, swingColors,
192                                          getString ("CTL_SwingPalette"), ce)
193             );
194             staticChooser.addChooserPanel (
195                 new NbColorChooserPanel (SYSTEM_PALETTE, getSystemColorNames(), systemColors,
196                                          getString ("CTL_SystemPalette"), ce)
197             );
198         return staticChooser;
199     }
200
201     // init .......................................................................................
202

203     /** Creates color editor. */
204     public ColorEditor() {
205         support = new PropertyChangeSupport JavaDoc (this);
206     }
207
208
209     // main methods .......................................................................................
210

211     /** Gets value. Implements <code>PropertyEditor</code> interface.
212      * @return <code>Color</code> value or <code>null</code> */

213     public Object JavaDoc getValue () {
214         if (superColor != null) {
215             if (superColor.getID () != null) {
216                 return superColor;
217             } else {
218                 return superColor.getColor ();
219             }
220             
221         } else {
222             return null;
223         }
224     }
225
226     /** Sets value. Implements <code>PropertyEditor</code> interface.
227      * @param object object to set, accepts <code>Color</code>
228      * or <code>SuperColor<code> types */

229     public void setValue (Object JavaDoc object) {
230         if(object != null) {
231             if (object instanceof SuperColor) {
232                 superColor = (SuperColor) object;
233             }
234             else if (object instanceof Color JavaDoc) {
235                 superColor = new SuperColor((Color JavaDoc) object);
236             }
237         }
238         else {
239             superColor = null;
240         }
241
242         support.firePropertyChange ("", null, null); // NOI18N
243
}
244
245     /** Gets value as text. Implements <code>PropertyEditor</code> interface. */
246     public String JavaDoc getAsText () {
247         if (superColor == null)
248             return "null"; // NOI18N
249
return superColor.getAsText ();
250     }
251
252     /** Sets value ad text. Implements <code>PropertyEditor</code> interface. */
253     public void setAsText(String JavaDoc text) throws IllegalArgumentException JavaDoc {
254         if(text == null) {
255             throw new IllegalArgumentException JavaDoc("null parameter"); // NOI18N
256
}
257         
258         text = text.trim();
259         
260         if("null".equals(text)) { // NOI18N
261
setValue(null);
262             return;
263         }
264
265         try { // try to extract RGB values - represented as [r,g,b] or r,g,b
266
int len = text.length();
267             if (len > 0) {
268                 int start = -1;
269                 int end = -1;
270
271                 char c1 = text.charAt(0);
272                 char c2 = text.charAt(len-1);
273                 if (c1 == '[' && c2 == ']') {
274                     start = 1;
275                     end = len - 1;
276                 }
277                 else if (c1 >= '0' && c1 <= '9' && c2 >= '0' && c2 <= '9') {
278                     start = 0;
279                     end = len;
280                 }
281
282                 if (start >= 0) {
283                     int index1 = text.indexOf(',');
284                     int index2 = index1 < 0 ? -1 : text.indexOf(',', index1+1);
285
286                     if (index1 >= 0 && index2 >= 0) {
287                         int red = Integer.parseInt(text.substring(
288                                                         start, index1).trim());
289                         int green = Integer.parseInt(text.substring(
290                                                           index1 + 1, index2).trim());
291                         int blue = Integer.parseInt(text.substring(
292                                                          index2 + 1, end).trim());
293
294                         try {
295                             setValue(new SuperColor(null,
296                                                     0,
297                                                     new Color JavaDoc(red, green, blue)));
298                             return;
299                         } catch( IllegalArgumentException JavaDoc iaE ) {
300                             UIExceptions.annotateUser(iaE, null,
301                                                      iaE.getLocalizedMessage(),
302                                                      null, null);
303                             throw iaE;
304                         }
305                     }
306                 }
307             }
308         } catch(NumberFormatException JavaDoc nfe) {
309             // Ignore it and try out from palette's next.
310
}
311  
312         int index;
313         int palette = 0;
314         Color JavaDoc color = null;
315
316         if((index = getIndex(getAWTColorNames(), text)) >= 0) {
317             palette = AWT_PALETTE;
318             color = awtColors[index];
319         }
320
321         if(index < 0 && ((index = getIndex(getSystemColorNames(), text)) >= 0)) {
322             palette = SYSTEM_PALETTE;
323             color = systemColors[index];
324         }
325
326         if(index < 0) {
327             initSwingConstants();
328             if((index = getIndex(swingColorNames, text)) >= 0) {
329                 palette = SWING_PALETTE;
330                 color = swingColors[index];
331             }
332         }
333
334         if(index < 0) {
335             String JavaDoc msg = MessageFormat.format (
336                 NbBundle.getMessage (ColorEditor.class, "FMT_IllegalEntry"),
337                 new Object JavaDoc[]{text});
338             IllegalArgumentException JavaDoc iae = new IllegalArgumentException JavaDoc (text);
339             UIExceptions.annotateUser(iae, text, msg, null, null);
340             throw iae;
341         }
342
343         setValue(new SuperColor(text, palette, color));
344     }
345
346     /** Gets java inititalization string. Implements <code>PropertyEditor</code> interface. */
347     public String JavaDoc getJavaInitializationString() {
348         if (superColor == null)
349             return "null"; // NOI18N
350
if (superColor.getID() == null)
351             return "new java.awt.Color(" + superColor.getRed() + ", " + superColor.getGreen() + // NOI18N
352
", " + superColor.getBlue() + ")"; // NOI18N
353

354         switch (superColor.getPalette()) {
355         default:
356         case AWT_PALETTE:
357             return "java.awt.Color." + awtGenerate [getIndex (getAWTColorNames(), superColor.getID())]; // NOI18N
358
case SYSTEM_PALETTE:
359             return "java.awt.SystemColor." + systemGenerate [getIndex (getSystemColorNames(), superColor.getID())]; // NOI18N
360
case SWING_PALETTE:
361             if (superColor.getID() == null) return "new java.awt.Color(" + superColor.getRed() + ", " + superColor.getGreen() + // NOI18N
362
", " + superColor.getBlue() + ")"; // NOI18N
363
return "javax.swing.UIManager.getDefaults().getColor(\"" + // NOI18N
364
superColor.getID() + "\")"; // NOI18N
365
}
366     }
367
368     /** Get tags possible for choosing value. Implements <code>PropertyEditor</code> interface. */
369     public String JavaDoc[] getTags() {
370         if (superColor == null) {
371             return getAWTColorNames();
372         }
373         switch (superColor.getPalette()) {
374             case AWT_PALETTE:
375                 return getAWTColorNames();
376             case SYSTEM_PALETTE:
377                 return getSystemColorNames();
378             case SWING_PALETTE:
379                 initSwingConstants();
380                 return swingColorNames;
381             default:
382                 return null;
383         }
384     }
385
386     /** Insicates whether this editor is paintable. Implements <code>PropertyEditor</code> interface.
387      * @return <code>true</code> */

388     public boolean isPaintable () {
389         return true;
390     }
391
392     /** Paints the current value. Implements <code>ProepertyEditor</code> interface. */
393     public void paintValue(Graphics JavaDoc g, Rectangle JavaDoc rectangle) {
394         int px;
395
396         ((Graphics2D JavaDoc)g).setRenderingHints (getHints ());
397         
398         if (this.superColor != null) {
399             Color JavaDoc color = g.getColor();
400             g.drawRect(rectangle.x, rectangle.y + rectangle.height / 2 - 5 , 10, 10);
401             g.setColor(this.superColor);
402             g.fillRect(rectangle.x + 1, rectangle.y + rectangle.height / 2 - 4 , 9, 9);
403             g.setColor(color);
404             px = 18;
405         }
406         else px = 0;
407
408         FontMetrics JavaDoc fm = g.getFontMetrics();
409         g.drawString(getAsText(), rectangle.x + px, rectangle.y +
410                       (rectangle.height - fm.getHeight()) / 2 + fm.getAscent());
411     }
412
413     /** Indicates whether this editor supports custom editing.
414      * Implements <code>PropertyEditor</code> interface.
415      * @return <code>true</code> */

416     public boolean supportsCustomEditor () {
417         return true;
418     }
419
420     /** Gets custom editor. Implements <code>PropertyEditor</code> interface.
421      * *return <code>NbColorChooser</code> instance */

422     public Component JavaDoc getCustomEditor () {
423         return new NbColorChooser (this, getStaticChooser(this));
424     }
425
426     /** Adds property change listener. */
427     public void addPropertyChangeListener (PropertyChangeListener JavaDoc propertyChangeListener) {
428         support.addPropertyChangeListener (propertyChangeListener);
429     }
430
431     /** Removes property change listner. */
432     public void removePropertyChangeListener (PropertyChangeListener JavaDoc propertyChangeListener) {
433         support.removePropertyChangeListener (propertyChangeListener);
434     }
435
436     // helper methods .......................................................................................
437
/** Gets array of localized AWT color names. */
438     private static synchronized String JavaDoc[] getAWTColorNames() {
439         if(awtColorNames == null) {
440             awtColorNames = new String JavaDoc[] {
441                 getString("LAB_White"),
442                 getString("LAB_LightGray"),
443                 getString("LAB_Gray"),
444                 getString("LAB_DarkGray"),
445                 getString("LAB_Black"),
446                 getString("LAB_Red"),
447                 getString("LAB_Pink"),
448                 getString("LAB_Orange"),
449                 getString("LAB_Yellow"),
450                 getString("LAB_Green"),
451                 getString("LAB_Magenta"),
452                 getString("LAB_Cyan"),
453                 getString("LAB_Blue")
454             };
455         }
456         
457         return awtColorNames;
458     }
459
460     /** Gets array of localize system color names. */
461     private static synchronized String JavaDoc[] getSystemColorNames() {
462         if(systemColorNames == null) {
463             systemColorNames = new String JavaDoc[] {
464                 getString("LAB_ActiveCaption"),
465                 getString("LAB_ActiveCaptionBorder"),
466                 getString("LAB_ActiveCaptionText"),
467                 getString("LAB_Control"),
468                 getString("LAB_ControlDkShadow"),
469                 getString("LAB_ControlHighlight"),
470                 getString("LAB_ControlLtHighlight"),
471                 getString("LAB_ControlShadow"),
472                 getString("LAB_ControlText"),
473                 getString("LAB_Desktop"),
474                 getString("LAB_InactiveCaption"),
475                 getString("LAB_InactiveCaptionBorder"),
476                 getString("LAB_InactiveCaptionText"),
477                 getString("LAB_Info"),
478                 getString("LAB_InfoText"),
479                 getString("LAB_Menu"),
480                 getString("LAB_MenuText"),
481                 getString("LAB_Scrollbar"),
482                 getString("LAB_Text"),
483                 getString("LAB_TextHighlight"),
484                 getString("LAB_TextHighlightText"),
485                 getString("LAB_TextInactiveText"),
486                 getString("LAB_TextText"),
487                 getString("LAB_Window"),
488                 getString("LAB_WindowBorder"),
489                 getString("LAB_WindowText")
490             };
491         }
492         
493         return systemColorNames;
494     }
495
496     /** Gets localized string.
497      * @param key key from bundle from the package like this source */

498     private static String JavaDoc getString(String JavaDoc key) {
499         return NbBundle.getBundle(ColorEditor.class).getString(key);
500     }
501
502     /** Gets index of name from array. */
503     private static int getIndex (Object JavaDoc[] names, Object JavaDoc name) {
504         for(int i = 0; i < names.length; i++) {
505             if(name.equals(names[i])) {
506                 return i;
507             }
508         }
509         
510         return -1;
511     }
512
513     /** Initialized fields used in Swing Palette. */
514     private static void initSwingConstants() {
515         if (swingColorNames != null)
516             return;
517
518         UIDefaults JavaDoc def = UIManager.getDefaults ();
519         Enumeration JavaDoc e = def.keys ();
520         
521         java.util.TreeSet JavaDoc<String JavaDoc> names = new java.util.TreeSet JavaDoc<String JavaDoc>();
522         
523         while (e.hasMoreElements ()) {
524             Object JavaDoc k = e.nextElement ();
525             if (! (k instanceof String JavaDoc))
526                 continue;
527             Object JavaDoc v = def.get (k);
528             if (! (v instanceof Color JavaDoc))
529                 continue;
530             names.add((String JavaDoc)k);
531         }
532         
533         swingColorNames = new String JavaDoc [names.size ()];
534         names.toArray(swingColorNames);
535         swingColors = new Color JavaDoc [swingColorNames.length];
536         
537         int i, k = swingColorNames.length;
538         for (i = 0; i < k; i++)
539             swingColors [i] = (Color JavaDoc) def.get (swingColorNames [i]);
540             }
541
542     private SuperColor getSuperColor () {
543         return superColor;
544     }
545
546
547     // innerclasses ............................................................................................
548
/** Panel used as custom property editor. */
549     private static class NbColorChooser extends JPanel JavaDoc implements ChangeListener JavaDoc {
550         /** Color property editor */
551         private final ColorEditor editor;
552         /** Reference to model which holds the color selected in the color chooser */
553         private final ColorSelectionModel JavaDoc selectionModel;
554
555         static final long serialVersionUID =-6230228701104365037L;
556         
557         
558         /** Creates new <code>NbColorChooser</code>. */
559         public NbColorChooser (final ColorEditor editor,
560                                final JColorChooser JavaDoc chooser) {
561             this.editor = editor;
562             selectionModel = chooser.getSelectionModel();
563             setLayout (new BorderLayout JavaDoc ());
564             add (chooser, BorderLayout.CENTER);
565             chooser.setColor ((Color JavaDoc)editor.getValue ());
566             selectionModel.addChangeListener (this);
567             
568             getAccessibleContext().setAccessibleDescription(getString("ACSD_CustomColorEditor"));
569         }
570
571         /** Overrides superclass method. Adds removing of change listener. */
572         public void removeNotify () {
573             super.removeNotify();
574             selectionModel.removeChangeListener (this);
575         }
576
577         /** Overrides superclass method. Adds 50 pixels to each side. */
578         public Dimension JavaDoc getPreferredSize () {
579             Dimension JavaDoc s = super.getPreferredSize ();
580             return new Dimension JavaDoc (s.width + 50, s.height + 10);
581         }
582
583         /** Implementats <code>ChangeListener</code> interface */
584         public void stateChanged (ChangeEvent JavaDoc evt) {
585             editor.setValue(selectionModel.getSelectedColor());
586         }
587
588     } // End of class NbColorChooser.
589

590
591     /** Color belonging to palette and keeping its ID. */
592     static class SuperColor extends Color JavaDoc {
593         /** generated Serialized Version UID */
594         static final long serialVersionUID = 6147637669184334151L;
595
596         /** ID of this color. */
597         private String JavaDoc id = null;
598         /** Palette where it belongs. */
599         private int palette = 0;
600
601         private Color JavaDoc color;
602
603         SuperColor (Color JavaDoc color) {
604             super (color.getRed (), color.getGreen (), color.getBlue ());
605             this.color = color;
606             
607             //jkozak: When user sets color by RGB values, maybe we shouldn't
608
// change the color to AWT-Palette constant.
609
/*
610             int i = getIndex (ColorEditor.awtColors, color);
611             if (i < 0) return;
612             id = getAWTColorNames()[i];
613              */

614         }
615
616         SuperColor (String JavaDoc id, int palette, Color JavaDoc color) {
617             super (color.getRed (), color.getGreen (), color.getBlue ());
618             this.color = color;
619             this.id = id;
620             this.palette = palette;
621         }
622
623         /** Overrides the equals(Object obj) method of java.awt.Color */
624         public boolean equals(Object JavaDoc obj) {
625             boolean superEquals = super.equals(obj);
626             String JavaDoc objID = null;
627             int objPalette = -1;
628             
629             if (obj instanceof SuperColor) {
630                 objID = ((SuperColor)obj).getID();
631                 objPalette = ((SuperColor)obj).getPalette();
632             }
633             else return superEquals;
634             
635             if (objID != null) {
636                 return superEquals && objID.equals(getID()) && (objPalette == getPalette());
637             }
638             else {
639                 return superEquals && (null == getID()) && (objPalette == getPalette());
640             }
641         }
642
643         /** Gets ID of this color. */
644         private String JavaDoc getID () {
645             return id;
646         }
647
648         /** Gets palette of this color. */
649         private int getPalette () {
650             return palette;
651         }
652
653         /** Returns original color object */
654         private Color JavaDoc getColor () {
655             return this.color;
656         }
657
658         /** Gets as text this color value. */
659         private String JavaDoc getAsText () {
660             if (id != null) return id;
661             return "[" + getRed () + "," + getGreen () + "," + getBlue () + "]"; // NOI18N
662
}
663     } // End of class SuperColor.
664

665     /** Color chooser panel which can be added into JColorChooser */
666     private static final class NbColorChooserPanel extends AbstractColorChooserPanel JavaDoc
667     implements ListSelectionListener {
668         /** Generated Serialized Version UID */
669         static final long serialVersionUID = -2792992315444428631L;
670         /** List holding palette colors */
671         private JList JavaDoc list;
672
673         /** Arraay of names of colors. */
674         String JavaDoc [] names;
675         /** Arraay of colors. */
676         Color JavaDoc [] colors;
677         /** Palette type. */
678         int palette;
679         /** Current ColorEditor. */
680         ColorEditor ce;
681         
682         /** Name for display of this chooser panel. */
683         private String JavaDoc displayName;
684         
685
686         /** Constructs our chooser panel with specified
687         * palette, names and colors to be shown in the list */

688         NbColorChooserPanel (final int palette, final String JavaDoc[] names,
689                              final Color JavaDoc[] colors, final String JavaDoc displayName, final ColorEditor ce) {
690             this.names = names;
691             this.colors = colors;
692             this.palette = palette;
693             this.displayName = displayName;
694             this.ce = ce;
695         }
696
697         /** Builds - creates a chooser */
698         protected void buildChooser () {
699             setLayout (new BorderLayout JavaDoc ());
700             add (BorderLayout.CENTER,
701                  new JScrollPane JavaDoc (list = new JList JavaDoc (names)));
702             list.setCellRenderer (new MyListCellRenderer ());
703             list.addListSelectionListener (this);
704             
705             list.getAccessibleContext().setAccessibleName(displayName);
706         }
707
708         /** Get called when state of selected color changes */
709         public void updateChooser () {
710             SuperColor sc = ce.getSuperColor ();
711             
712             if (sc != null && palette == sc.getPalette ()) {
713                 int i = getIndex (names, sc.getID ());
714                 list.setSelectedIndex (i);
715             } else
716                 list.clearSelection ();
717         }
718
719         /** @return display name of the chooser */
720         public String JavaDoc getDisplayName() {
721             return displayName;
722         }
723
724         /** No icon */
725         public Icon JavaDoc getSmallDisplayIcon() {
726             return null;
727         }
728
729         /** No icon */
730         public Icon JavaDoc getLargeDisplayIcon() {
731             return null;
732         }
733
734         /** ListSelectionListener interface implementation */
735         public void valueChanged(ListSelectionEvent e) {
736             if (!list.isSelectionEmpty ()) {
737                 int i = list.getSelectedIndex ();
738                 getColorSelectionModel().setSelectedColor(
739                     new SuperColor (names [i], palette, colors [i]));
740             }
741         }
742
743         /** Setter for <code>color</code> property. */
744         public void setColor (final Color JavaDoc newColor) {
745             getColorSelectionModel().setSelectedColor(newColor);
746         }
747
748         /** Getter for <code>color</code> property. */
749         public Color JavaDoc getColor () {
750             return getColorFromModel();
751         }
752
753         
754         /** Renderer for cell of the list showing palette colors */
755         private final class MyListCellRenderer extends JPanel JavaDoc implements ListCellRenderer JavaDoc {
756
757             /** Selected flag. */
758             private boolean selected;
759             /** Focus flag. */
760             private boolean hasFocus;
761             /** Selected index. */
762             private int index;
763
764             /** Generated serial version UID. */
765             static final long serialVersionUID =-8877709520578055594L;
766             
767             
768             /** Creates a new MyListCellRenderer */
769             public MyListCellRenderer () {
770                 this.setOpaque (true);
771                 this.setBorder (new EmptyBorder JavaDoc (1, 1, 1, 1));
772             }
773
774             /** Overrides default preferredSize impl.
775              * @return Standard method returned preferredSize
776              * (depends on font size only).
777              */

778             public Dimension JavaDoc getPreferredSize () {
779                 try {
780                     FontMetrics JavaDoc fontMetrics = this.getFontMetrics(this.getFont());
781                     return new Dimension JavaDoc (
782                                fontMetrics.stringWidth (names [index]) + 30,
783                                fontMetrics.getHeight () + 4
784                            );
785                 } catch (NullPointerException JavaDoc e) {
786                     return new Dimension JavaDoc (10, 10);
787                 }
788             }
789
790             /** Paints this component. Overrides superclass method. */
791             public void paint (Graphics JavaDoc g) {
792                 ((Graphics2D JavaDoc)g).setRenderingHints (getHints ());
793                 
794                 Dimension JavaDoc rectangle = this.getSize ();
795                 Color JavaDoc color = g.getColor ();
796
797                 if(selected) {
798                     g.setColor (UIManager.getColor ("List.selectionBackground")); // NOI18N
799
} else {
800                     g.setColor (UIManager.getColor ("List.background")); // NOI18N
801
}
802                 
803                 g.fillRect (0, 0, rectangle.width - 1, rectangle.height - 1);
804
805                 if (hasFocus) {
806                     g.setColor (Color.black);
807                     g.drawRect (0, 0, rectangle.width - 1, rectangle.height - 1);
808                 }
809
810                 g.setColor (Color.black);
811                 g.drawRect (6, rectangle.height / 2 - 5 , 10, 10);
812                 g.setColor (colors [index]);
813                 g.fillRect (7, rectangle.height / 2 - 4 , 9, 9);
814                 
815                 if(selected) {
816                     g.setColor (UIManager.getColor ("List.selectionForeground")); // NOI18N
817
} else {
818                     g.setColor (UIManager.getColor ("List.foreground")); // NOI18N
819
}
820                 
821                 FontMetrics JavaDoc fm = g.getFontMetrics ();
822                 g.drawString (names [index], 22, (rectangle.height - fm.getHeight ()) / 2 + fm.getAscent ());
823                 g.setColor (color);
824             }
825
826             /** This is the only method defined by ListCellRenderer. We just
827              * reconfigure the Jlabel each time we're called.
828              */

829             public Component JavaDoc getListCellRendererComponent (
830                 JList JavaDoc list,
831                 Object JavaDoc value, // value to display
832
int index, // cell index
833
boolean isSelected, // is the cell selected
834
boolean cellHasFocus // the list and the cell have the focus
835
) {
836                 this.index = index;
837                 selected = isSelected;
838                 hasFocus = cellHasFocus;
839                 getAccessibleContext().setAccessibleName(names[index]);
840                 return this;
841             }
842         } // End of class MyListCellRenderer.
843
} // End of class NbColorChooserPanel.
844

845     //--------------------------------------------------------------------------
846
// XMLPropertyEditor implementation
847

848     /** Name of color element. */
849     public static final String JavaDoc XML_COLOR = "Color"; // NOI18N
850

851     /** Name of type attribute. */
852     public static final String JavaDoc ATTR_TYPE = "type"; // NOI18N
853
/** Name of red attribute. */
854     public static final String JavaDoc ATTR_RED = "red"; // NOI18N
855
/** Name of green attribute. */
856     public static final String JavaDoc ATTR_GREEN = "green"; // NOI18N
857
/** Name of blue attribute. */
858     public static final String JavaDoc ATTR_BLUE = "blue"; // NOI18N
859
/** Name of id attribute. */
860     public static final String JavaDoc ATTR_ID = "id"; // NOI18N
861
/** Name of palette attribute. */
862     public static final String JavaDoc ATTR_PALETTE = "palette"; // NOI18N
863

864     /** Value of palette. */
865     public static final String JavaDoc VALUE_PALETTE = "palette"; // NOI18N
866
/** Value of rgb. */
867     public static final String JavaDoc VALUE_RGB = "rgb"; // NOI18N
868
/** Null value. */
869     public static final String JavaDoc VALUE_NULL = "null"; // NOI18N
870

871     
872     /** Called to load property value from specified XML subtree. If succesfully loaded,
873      * Implements <code>XMLPropertyEditor</code> interface.
874      * the value should be available via the getValue method.
875      * An IOException should be thrown when the value cannot be restored from the specified XML element
876      * @param element the XML DOM element representing a subtree of XML from which the value should be loaded
877      * @exception IOException thrown when the value cannot be restored from the specified XML element
878      */

879     public void readFromXML (org.w3c.dom.Node JavaDoc element) throws java.io.IOException JavaDoc {
880         if (!XML_COLOR.equals (element.getNodeName ())) {
881             throw new java.io.IOException JavaDoc ();
882         }
883         org.w3c.dom.NamedNodeMap JavaDoc attributes = element.getAttributes ();
884         try {
885             String JavaDoc type = attributes.getNamedItem (ATTR_TYPE).getNodeValue ();
886             if (VALUE_NULL.equals(type)) {
887                 setValue(null);
888             } else {
889                 String JavaDoc red = attributes.getNamedItem (ATTR_RED).getNodeValue ();
890                 String JavaDoc green = attributes.getNamedItem (ATTR_GREEN).getNodeValue ();
891                 String JavaDoc blue = attributes.getNamedItem (ATTR_BLUE).getNodeValue ();
892                 if (VALUE_PALETTE.equals (type)) {
893                     String JavaDoc id = attributes.getNamedItem (ATTR_ID).getNodeValue ();
894                     String JavaDoc palette = attributes.getNamedItem (ATTR_PALETTE).getNodeValue ();
895                     setValue (new SuperColor (id, Integer.parseInt (palette), new Color JavaDoc (Integer.parseInt (red, 16), Integer.parseInt (green, 16), Integer.parseInt (blue, 16))));
896                 } else {
897                     setValue (new SuperColor (new Color JavaDoc (Integer.parseInt (red, 16), Integer.parseInt (green, 16), Integer.parseInt (blue, 16))));
898                 }
899             }
900         } catch (NullPointerException JavaDoc e) {
901             throw new java.io.IOException JavaDoc ();
902         }
903     }
904
905     /** Called to store current property value into XML subtree. The property value should be set using the
906      * Implemtns <code>XMLPropertyEdtitor</code> interface.
907      * setValue method prior to calling this method.
908      * @param doc The XML document to store the XML in - should be used for creating nodes only
909      * @return the XML DOM element representing a subtree of XML from which the value should be loaded
910      */

911     public org.w3c.dom.Node JavaDoc storeToXML(org.w3c.dom.Document JavaDoc doc) {
912         org.w3c.dom.Element JavaDoc el = doc.createElement (XML_COLOR);
913         el.setAttribute (ATTR_TYPE, (superColor == null) ? VALUE_NULL : ((superColor.getID () == null) ? VALUE_RGB : VALUE_PALETTE));
914         if (superColor != null) {
915             el.setAttribute (ATTR_RED, Integer.toHexString (superColor.getRed ()));
916             el.setAttribute (ATTR_GREEN, Integer.toHexString (superColor.getGreen ()));
917             el.setAttribute (ATTR_BLUE, Integer.toHexString (superColor.getBlue ()));
918             if (superColor.getID () != null) {
919                 el.setAttribute (ATTR_ID, superColor.getID ());
920                 el.setAttribute (ATTR_PALETTE, Integer.toString (superColor.getPalette ()));
921             }
922         }
923         return el;
924     }
925
926     public static final boolean gtkShouldAntialias() {
927         if (gtkAA == null) {
928             Object JavaDoc o = Toolkit.getDefaultToolkit().getDesktopProperty("gnome.Xft/Antialias"); //NOI18N
929
gtkAA = Boolean.valueOf(Integer.valueOf(1).equals(o));
930         }
931
932         return gtkAA.booleanValue();
933     }
934
935     // copied from openide/awt/HtmlLabelUI
936
private static Map JavaDoc getHints () {
937         if (hintsMap == null) {
938             hintsMap = (Map JavaDoc)(Toolkit.getDefaultToolkit().getDesktopProperty("awt.font.desktophints")); //NOI18N
939
if (hintsMap == null) {
940                 hintsMap = new HashMap JavaDoc();
941                 if (antialias) {
942                     hintsMap.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
943                 }
944             }
945         }
946         return hintsMap;
947     }
948 }
949
Popular Tags