KickJava   Java API By Example, From Geeks To Geeks.

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


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.beaninfo.editors;
21
22 import java.awt.*;
23 import java.awt.event.*;
24 import java.beans.*;
25
26 import javax.swing.*;
27 import javax.swing.border.*;
28 import javax.swing.event.*;
29 import org.openide.DialogDisplayer;
30
31 import org.openide.NotifyDescriptor;
32 import org.openide.awt.Mnemonics;
33 import org.openide.explorer.propertysheet.editors.XMLPropertyEditor;
34 import org.openide.util.Exceptions;
35 import org.openide.util.NbBundle;
36 import org.openide.util.Utilities;
37
38 /**
39 * A property editor for Font class.
40 *
41 * @author Ian Formanek
42 */

43 public class FontEditor implements PropertyEditor, XMLPropertyEditor {
44
45     // static .....................................................................................
46

47     static final Integer JavaDoc[] sizes = new Integer JavaDoc [] {
48                                        Integer.valueOf (3),
49                                        Integer.valueOf (5),
50                                        Integer.valueOf (8),
51                                        Integer.valueOf (10),
52                                        Integer.valueOf (12),
53                                        Integer.valueOf (14),
54                                        Integer.valueOf (18),
55                                        Integer.valueOf (24),
56                                        Integer.valueOf (36),
57                                        Integer.valueOf (48)
58                                    };
59
60     static final String JavaDoc[] styles = new String JavaDoc [] {
61                                        NbBundle.getMessage(FontEditor.class, "CTL_Plain"),
62                                        NbBundle.getMessage(FontEditor.class, "CTL_Bold"),
63                                        NbBundle.getMessage(FontEditor.class, "CTL_Italic"),
64                                        NbBundle.getMessage(FontEditor.class, "CTL_BoldItalic")
65                                    };
66
67     // variables ..................................................................................
68

69     private Font font;
70     private String JavaDoc fontName;
71     private PropertyChangeSupport support;
72
73
74     // init .......................................................................................
75

76     public FontEditor() {
77         support = new PropertyChangeSupport (this);
78     }
79
80
81     // main methods .......................................................................................
82

83     public Object JavaDoc getValue () {
84         return font;
85     }
86
87     public void setValue (Object JavaDoc object) {
88         if (font != null && font.equals (object)) {
89             return ;
90         } else if (font == null && object == null) {
91             return ;
92         }
93         
94         if (object instanceof Font) {
95             font = (Font) object;
96         } else if (object == null) {
97             font = null;
98         } else {
99             assert false : "Object " + object + " is instanceof Font or null";
100         }
101         
102         if (font != null) {
103             fontName = font.getName () + " " + font.getSize () + " " + getStyleName (font.getStyle ()); // NOI18N
104
} else {
105             fontName = null;
106         }
107         
108         support.firePropertyChange ("", null, null); // NOI18N
109
}
110
111     public String JavaDoc getAsText () {
112         return fontName;
113     }
114
115     public void setAsText (String JavaDoc string) {
116         return;
117     }
118
119     public String JavaDoc getJavaInitializationString () {
120         return "new java.awt.Font(\"" + font.getName () + "\", " + font.getStyle () + // NOI18N
121
", " + font.getSize () + ")"; // NOI18N
122
}
123
124     public String JavaDoc[] getTags () {
125         return null;
126     }
127
128     public boolean isPaintable () {
129         return true;
130     }
131
132     public void paintValue (Graphics g, Rectangle rectangle) {
133         Font originalFont = g.getFont ();
134         
135         // Fix of 21713, set default value
136
if ( font == null ) setValue( null );
137         
138         Font paintFont = font == null ? originalFont : font; // NOI18N
139
assert paintFont != null : "paintFont must exist.";
140         
141         FontMetrics fm = g.getFontMetrics (paintFont);
142         if (fm.getHeight() > rectangle.height) {
143             if (Utilities.isMac()) {
144                 // don't use deriveFont() - see #49973 for details
145
paintFont = new Font(paintFont.getName(), paintFont.getStyle(), 12);
146             } else {
147                 paintFont = paintFont.deriveFont(12f);
148             }
149             fm = g.getFontMetrics (paintFont);
150         }
151         g.setFont (paintFont);
152         g.drawString (fontName == null ? "null" : fontName, // NOI18N
153
rectangle.x,
154                       rectangle.y + (rectangle.height - fm.getHeight ()) / 2 + fm.getAscent ());
155         g.setFont (originalFont);
156     }
157
158     public boolean supportsCustomEditor () {
159         return true;
160     }
161
162     public Component getCustomEditor () {
163         return new FontPanel ();
164     }
165
166     public void addPropertyChangeListener (PropertyChangeListener propertyChangeListener) {
167         support.addPropertyChangeListener (propertyChangeListener);
168     }
169
170     public void removePropertyChangeListener (PropertyChangeListener propertyChangeListener) {
171         support.removePropertyChangeListener (propertyChangeListener);
172     }
173
174
175     // helper methods .......................................................................................
176

177     String JavaDoc getStyleName (int i) {
178         if ((i & Font.BOLD) > 0)
179             if ((i & Font.ITALIC) > 0) return NbBundle.getMessage(FontEditor.class, "CTL_BoldItalic");
180             else return NbBundle.getMessage(FontEditor.class, "CTL_Bold");
181         else
182             if ((i & Font.ITALIC) > 0) return NbBundle.getMessage(FontEditor.class, "CTL_Italic");
183             else return NbBundle.getMessage(FontEditor.class, "CTL_Plain");
184     }
185     
186     static private String JavaDoc[] fonts;
187     static private String JavaDoc [] getFonts () {
188         if (fonts == null) {
189             try {
190                 fonts = GraphicsEnvironment.getLocalGraphicsEnvironment ().getAvailableFontFamilyNames();
191             } catch (RuntimeException JavaDoc e) {
192                 fonts = new String JavaDoc[0]; //NOI18N
193
if (org.openide.util.Utilities.isMac()) {
194                     String JavaDoc msg = NbBundle.getMessage(FontEditor.class, "MSG_AppleBug"); //NOI18N
195
DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message(msg));
196                 } else {
197                     throw e;
198                 }
199             }
200         }
201         return fonts;
202     }
203
204
205     // innerclasses ............................................................................................
206

207     class FontPanel extends JPanel {
208
209         JTextField tfFont, tfStyle, tfSize;
210         JList lFont, lStyle, lSize;
211
212         static final long serialVersionUID =8377025140456676594L;
213
214         FontPanel () {
215             setLayout (new BorderLayout ());
216             setBorder(new EmptyBorder(12, 12, 0, 11));
217             
218             Font font = (Font) getValue ();
219             if (font == null) {
220                 if (getFonts ().length > 0) {
221                     font = new Font (fonts[0], Font.PLAIN, 10);
222                 } else {
223                     font = UIManager.getFont ("Label.font"); // NOI18N
224
}
225             }
226
227             lFont = new JList (getFonts ());
228             lFont.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FontEditor.class, "ACSD_CTL_Font"));
229             lStyle = new JList (styles);
230             lStyle.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FontEditor.class, "ACSD_CTL_FontStyle"));
231             lSize = new JList (sizes);
232             lSize.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FontEditor.class, "ACSD_CTL_Size"));
233             tfSize = new JTextField (String.valueOf(font.getSize ()));
234             tfSize.getAccessibleContext().setAccessibleDescription(lSize.getAccessibleContext().getAccessibleDescription());
235             getAccessibleContext().setAccessibleDescription(NbBundle.getMessage(FontEditor.class, "ACSD_FontCustomEditor"));
236
237             GridBagLayout la = new GridBagLayout ();
238             GridBagConstraints c = new GridBagConstraints ();
239             setLayout (la);
240
241             c.gridwidth = 1;
242             c.weightx = 1.0;
243             c.insets = new Insets (0, 0, 0, 0);
244             c.anchor = GridBagConstraints.WEST;
245             JLabel l = new JLabel ();
246             Mnemonics.setLocalizedText(l, NbBundle.getMessage(FontEditor.class, "CTL_Font")); //NoI18N
247
l.setLabelFor(lFont);
248             la.setConstraints (l, c);
249             add (l);
250
251             c.insets = new Insets (0, 5, 0, 0);
252             l = new JLabel (); //NoI18N
253
Mnemonics.setLocalizedText(l, NbBundle.getMessage(FontEditor.class, "CTL_FontStyle")); //NoI18N
254
l.setLabelFor(lStyle);
255             la.setConstraints (l, c);
256             add (l);
257
258             c.insets = new Insets (0, 5, 0, 0);
259             c.gridwidth = GridBagConstraints.REMAINDER;
260             l = new JLabel ();
261             Mnemonics.setLocalizedText(l, NbBundle.getMessage(FontEditor.class, "CTL_Size")); //NoI18N
262
l.setLabelFor(tfSize);
263             la.setConstraints (l, c);
264             add (l);
265
266             c.insets = new Insets (5, 0, 0, 0);
267             c.gridwidth = 1;
268             c.fill = GridBagConstraints.HORIZONTAL;
269             tfFont = new JTextField (font.getName ());
270             tfFont.setEnabled (false);
271             la.setConstraints (tfFont, c);
272             add (tfFont);
273
274             c.insets = new Insets (5, 5, 0, 0);
275             tfStyle = new JTextField (getStyleName (font.getStyle ()));
276             tfStyle.setEnabled (false);
277             la.setConstraints (tfStyle, c);
278             add (tfStyle);
279
280             c.insets = new Insets (5, 5, 0, 0);
281             c.gridwidth = GridBagConstraints.REMAINDER;
282             
283             tfSize.addKeyListener( new KeyAdapter() {
284                                     public void keyPressed(KeyEvent e) {
285                                         if ( e.getKeyCode() == KeyEvent.VK_ENTER )
286                                             setValue ();
287                                     }
288                                 });
289             
290             tfSize.addFocusListener (new FocusAdapter () {
291                                          public void focusLost (FocusEvent evt) {
292                                              setValue ();
293                                          }
294                                      });
295             la.setConstraints (tfSize, c);
296             add (tfSize);
297
298             c.gridwidth = 1;
299             c.insets = new Insets (5, 0, 0, 0);
300             c.fill = GridBagConstraints.BOTH;
301             c.weightx = 1.0;
302             c.weighty = 1.0;
303             lFont.setVisibleRowCount (5);
304             lFont.setSelectedValue(font.getName (), true);
305             lFont.addListSelectionListener (new ListSelectionListener () {
306                                                 public void valueChanged (ListSelectionEvent e) {
307                                                     if (!lFont.isSelectionEmpty ()) {
308                                                         if (getFonts ().length > 0) { //Mac bug workaround
309
int i = lFont.getSelectedIndex ();
310                                                             tfFont.setText (getFonts () [i]);
311                                                             setValue ();
312                                                         }
313                                                     }
314                                                 }
315                                             }
316                                            );
317             JScrollPane sp = new JScrollPane (lFont);
318             sp.setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
319             la.setConstraints (sp, c);
320             add (sp);
321
322             lStyle.setVisibleRowCount (5);
323             lStyle.setSelectedValue(getStyleName (font.getStyle ()), true);
324             lStyle.addListSelectionListener (new ListSelectionListener () {
325                                                  public void valueChanged (ListSelectionEvent e) {
326                                                      if (!lStyle.isSelectionEmpty ()) {
327                                                          int i = lStyle.getSelectedIndex ();
328                                                          tfStyle.setText (styles [i]);
329                                                          setValue ();
330                                                      }
331                                                  }
332                                              }
333                                             );
334             sp = new JScrollPane (lStyle);
335             sp.setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
336             c.insets = new Insets (5, 5, 0, 0);
337             la.setConstraints (sp, c);
338             add (sp);
339
340             c.gridwidth = GridBagConstraints.REMAINDER;
341             lSize.getAccessibleContext().setAccessibleName(tfSize.getAccessibleContext().getAccessibleName());
342             lSize.setVisibleRowCount (5);
343             updateSizeList(font.getSize ());
344             lSize.addListSelectionListener (new ListSelectionListener () {
345                                                 public void valueChanged (ListSelectionEvent e) {
346                                                     if (!lSize.isSelectionEmpty ()) {
347                                                         int i = lSize.getSelectedIndex ();
348                                                         tfSize.setText (String.valueOf(sizes [i]));
349                                                         setValue ();
350                                                     }
351                                                 }
352                                             }
353                                            );
354             sp = new JScrollPane (lSize);
355             sp.setVerticalScrollBarPolicy (JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
356             c.insets = new Insets (5, 5, 0, 0);
357             la.setConstraints (sp, c);
358             add (sp);
359
360             c.gridwidth = GridBagConstraints.REMAINDER;
361             c.weighty = 2.0;
362             JPanel p = new JPanel (new BorderLayout());
363             p.setBorder (new TitledBorder (" " + NbBundle.getMessage(FontEditor.class, "CTL_Preview") + " "));
364
365             JPanel pp = new JPanel () {
366                             public Dimension getPreferredSize () {
367                                 return new Dimension (150, 60);
368                             }
369
370                             public void paint (Graphics g) {
371                                 // super.paint (g);
372
FontEditor.this.paintValue (g, new Rectangle (0, 0, this.getSize().width - 1, this.getSize().height - 1));
373                             }
374                         };
375             p.add ("Center", pp); // NOI18N
376
c.insets = new Insets (12, 0, 0, 0);
377             la.setConstraints (p, c);
378             add (p);
379         }
380
381         public Dimension getPreferredSize () {
382             return new Dimension (400, 250);
383         }
384
385         private void updateSizeList(int size) {
386             if (java.util.Arrays.asList(sizes).contains(Integer.valueOf(size)))
387                 lSize.setSelectedValue(Integer.valueOf(size), true);
388             else
389                 lSize.clearSelection();
390         }
391
392         void setValue () {
393             int size = 12;
394             try {
395                 size = Integer.parseInt (tfSize.getText ());
396                 updateSizeList(size);
397             } catch (NumberFormatException JavaDoc e) {
398                 return;
399             }
400             int i = lStyle.getSelectedIndex (), ii = Font.PLAIN;
401             switch (i) {
402             case 0: ii = Font.PLAIN;break;
403             case 1: ii = Font.BOLD;break;
404             case 2: ii = Font.ITALIC;break;
405             case 3: ii = Font.BOLD | Font.ITALIC;break;
406             }
407             FontEditor.this.setValue (new Font (tfFont.getText (), ii, size));
408             invalidate();
409             java.awt.Component JavaDoc p = getParent();
410             if (p != null) {
411                 p.validate();
412             }
413             repaint();
414         }
415     }
416
417     //--------------------------------------------------------------------------
418
// XMLPropertyEditor implementation
419

420     public static final String JavaDoc XML_FONT = "Font"; // NOI18N
421

422     public static final String JavaDoc ATTR_NAME = "name"; // NOI18N
423
public static final String JavaDoc ATTR_STYLE = "style"; // NOI18N
424
public static final String JavaDoc ATTR_SIZE = "size"; // NOI18N
425

426     /** Called to load property value from specified XML subtree. If succesfully loaded,
427     * the value should be available via the getValue method.
428     * An IOException should be thrown when the value cannot be restored from the specified XML element
429     * @param element the XML DOM element representing a subtree of XML from which the value should be loaded
430     * @exception IOException thrown when the value cannot be restored from the specified XML element
431     */

432     public void readFromXML (org.w3c.dom.Node JavaDoc element) throws java.io.IOException JavaDoc {
433         if (!XML_FONT.equals (element.getNodeName ())) {
434             throw new java.io.IOException JavaDoc ();
435         }
436         org.w3c.dom.NamedNodeMap JavaDoc attributes = element.getAttributes ();
437         try {
438             String JavaDoc name = attributes.getNamedItem (ATTR_NAME).getNodeValue ();
439             String JavaDoc style = attributes.getNamedItem (ATTR_STYLE).getNodeValue (); // [PENDING - style names]
440
String JavaDoc size = attributes.getNamedItem (ATTR_SIZE).getNodeValue ();
441             setValue (new Font (name, Integer.parseInt (style), Integer.parseInt (size)));
442         } catch (NullPointerException JavaDoc e) {
443             throw new java.io.IOException JavaDoc ();
444         }
445     }
446
447     /** Called to store current property value into XML subtree. The property value should be set using the
448     * setValue method prior to calling this method.
449     * @param doc The XML document to store the XML in - should be used for creating nodes only
450     * @return the XML DOM element representing a subtree of XML from which the value should be loaded
451     */

452     public org.w3c.dom.Node JavaDoc storeToXML(org.w3c.dom.Document JavaDoc doc) {
453         if (font == null) {
454             IllegalArgumentException JavaDoc iae = new IllegalArgumentException JavaDoc();
455             Exceptions.attachLocalizedMessage(iae,
456                                               NbBundle.getMessage(FontEditor.class,
457                                                                   "MSG_FontIsNotInitialized")); // NOI18N
458
Exceptions.printStackTrace(iae);
459             return null;
460         }
461         
462         org.w3c.dom.Element JavaDoc el = doc.createElement (XML_FONT);
463         el.setAttribute (ATTR_NAME, font.getName ());
464         el.setAttribute (ATTR_STYLE, Integer.toString (font.getStyle ()));
465         el.setAttribute (ATTR_SIZE, Integer.toString (font.getSize ()));
466         return el;
467     }
468
469 }
470
Popular Tags