KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > suberic > util > swing > JFontChooser


1 package net.suberic.util.swing;
2
3 import java.awt.*;
4 import javax.swing.*;
5 import javax.swing.event.*;
6 import java.awt.event.*;
7
8 /**
9  * A panel which allows the user to select a Font from the list of all
10  * available fonts on the system.
11  */

12 public class JFontChooser extends JComponent {
13
14   JList fontList = null;
15   JList styleList = null;
16   JList sizeList = null;
17
18   JTextArea previewTextArea = null;
19
20   boolean changing = false;
21
22   Font originalFont = null;
23
24   Font selectedFont = null;
25
26   private static String JavaDoc[] allowedFontSizes = new String JavaDoc[] {
27     "6", "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "36",
28     "48", "72"
29   };
30
31   private static String JavaDoc[] allowedFontStyles = new String JavaDoc[] {
32     "Plain", "Italic", "Bold", "Bold Italic"
33   };
34
35   /**
36    * Creates a new JFontChooser with a default font.
37    */

38   public JFontChooser() {
39     configureChooser(new Font("monospaced", Font.PLAIN, 12), "The quick brown fox jumped over the lazy god [sic].");
40   }
41
42   /**
43    * Creates a new JFontChooser with the specified font.
44    */

45   public JFontChooser(Font initialFont) {
46     configureChooser(initialFont, "The quick brown fox jumped over the lazy god [sic].");
47   }
48
49   /**
50    * Creates a new JFontChooser with the given preview phrase and a
51    * default font.
52    */

53   public JFontChooser(String JavaDoc previewPhrase) {
54     configureChooser(new Font("monospaced", Font.PLAIN, 12), previewPhrase);
55   }
56
57   /**
58    * Creates a new JFontChooser with the specified font and given
59    * preview phrase.
60    */

61   public JFontChooser(Font initialFont, String JavaDoc previewPhrase) {
62     configureChooser(initialFont, previewPhrase);
63   }
64
65   /**
66    * Creates and returns a new dialog containing the specified
67    * FontChooser pane along with "OK", "Cancel", and "Reset"
68    * buttons.
69    */

70   public static JDialog createDialog(Component parent, String JavaDoc title,
71                      boolean modal,
72                      JFontChooser chooserPane,
73                      ActionListener okListener,
74                      ActionListener cancelListener) {
75     JDialog returnValue = new JDialog( JOptionPane.getFrameForComponent(parent), title, modal);
76
77     returnValue.getContentPane().setLayout(new BoxLayout(returnValue.getContentPane(), BoxLayout.Y_AXIS));
78     returnValue.getContentPane().add(chooserPane);
79     returnValue.getContentPane().add(chooserPane.createButtonPanel(okListener, cancelListener, returnValue));
80     Container cp = returnValue.getContentPane();
81     if (cp instanceof JComponent) {
82       ((JComponent) cp).setBorder(BorderFactory.createEtchedBorder());
83     }
84     return returnValue;
85   }
86
87   /**
88    * Returns the currently selected Font.
89    */

90   public Font getFont() {
91     return previewTextArea.getFont();
92   }
93
94   /**
95    * Returns the currently selected Font in a String form which is
96    * compatible with <code>Font.decode(String)</code>.
97    */

98   public String JavaDoc getFontString() {
99     return encodeFont(getFont());
100   }
101
102   /**
103    * Encodes the given Font in a String form which is
104    * compatible with <code>Font.decode(String)</code>.
105    */

106   public static String JavaDoc encodeFont(Font f) {
107     StringBuffer JavaDoc returnBuffer = new StringBuffer JavaDoc();
108     returnBuffer.append(f.getName());
109     returnBuffer.append('-');
110     returnBuffer.append(getFontStyle(f));
111     returnBuffer.append('-');
112     returnBuffer.append(f.getSize());
113     return returnBuffer.toString();
114   }
115
116   /**
117    * Sets the currently selected Font to the given Font.
118    */

119   public void setFont(Font newFont) {
120     changing = true;
121
122     if (previewTextArea != null) {
123       if (newFont != null) {
124     if (fontList != null) {
125       String JavaDoc fontName = newFont.getName();
126       fontList.setSelectedValue(fontName, true);
127     }
128     
129     if (styleList != null) {
130       String JavaDoc style = getFontStyle(newFont);
131       if (style != null && style == "BoldItalic")
132         styleList.setSelectedValue("Bold Italic", true);
133       else
134         styleList.setSelectedValue(style, true);
135     }
136     
137     if (sizeList != null) {
138       String JavaDoc size = Integer.toString(newFont.getSize());
139       sizeList.setSelectedValue(size, true);
140     }
141     
142     previewTextArea.setFont(newFont);
143     
144       }
145     }
146     changing = false;
147     
148   }
149
150   /**
151    * Gets the Font style as a String.
152    */

153   public static String JavaDoc getFontStyle(Font f) {
154     int style = f.getStyle();
155
156     if (style == Font.PLAIN)
157       return (allowedFontStyles[0]);
158     else if (style == Font.BOLD)
159       return (allowedFontStyles[1]);
160     else if (style == Font.ITALIC)
161       return (allowedFontStyles[2]);
162     else if (style == Font.BOLD + Font.ITALIC)
163       return (allowedFontStyles[3]);
164     else
165       return(allowedFontStyles[0]);
166   }
167
168   /**
169    * Shows a modal font-chooser dialog and blocks until the
170    * dialog is hidden. If the user presses the "OK" button, then
171    * this method hides/disposes the dialog and returns the selected font.
172    * If the user presses the "Cancel" button or closes the dialog without
173    * pressing "OK", then this method hides/disposes the dialog and returns
174    * null.
175    */

176     public static Font showDialog(Component component, String JavaDoc title,
177                 Font initialFont) {
178
179       final JFontChooser jfc = new JFontChooser(initialFont);
180       ActionListener okListener = new ActionListener() {
181       public void actionPerformed(ActionEvent e) {
182         Font currentFont = jfc.getFont();
183         jfc.setSelectedFont(currentFont);
184       }
185     };
186
187       JDialog dialog = createDialog(component, title,
188                     true,
189                     jfc,
190                     okListener,
191                     null);
192
193       dialog.pack();
194       dialog.setVisible(true);
195
196       return jfc.getSelectedFont();
197   }
198
199   /**
200    * Shows a modal font-chooser dialog and blocks until the
201    * dialog is hidden. If the user presses the "OK" button, then
202    * this method hides/disposes the dialog and returns the String
203    * representation of the selected Font.
204    * If the user presses the "Cancel" button or closes the dialog without
205    * pressing "OK", then this method hides/disposes the dialog and returns
206    * null.
207    */

208     public static String JavaDoc showStringDialog(Component component, String JavaDoc title,
209                 Font initialFont) {
210       Font selectedFont = showDialog(component, title, initialFont);
211       if (selectedFont != null) {
212     return encodeFont(selectedFont);
213       }
214
215       return null;
216   }
217
218   /* private functions */
219
220   /**
221    * Configures a new JFontChooser.
222    */

223   private void configureChooser(Font f, String JavaDoc previewString) {
224     originalFont = f;
225     Box mainBox = Box.createVerticalBox();
226     mainBox.add(createChooserPanel(f));
227     mainBox.add(Box.createVerticalStrut(10));
228     mainBox.add(createPreviewPanel(f, previewString));
229     setFont(f);
230     this.setLayout(new BorderLayout());
231     this.add(mainBox, BorderLayout.CENTER);
232     //this.pack();
233
}
234
235   /**
236    * Creates the Chooser panel.
237    */

238   private Component createChooserPanel(Font f) {
239     JPanel returnValue = new JPanel();
240
241     ListSelectionListener changeListener = new ListSelectionListener() {
242     public void valueChanged(ListSelectionEvent lse) {
243       if (! changing)
244         fontSelectionChanged();
245         }
246       };
247
248     Box chooser = Box.createHorizontalBox();
249     
250     Box fontBox = Box.createVerticalBox();
251     fontBox.add(new JLabel("Font"));
252     fontList = new JList(getFontNames());
253     fontList.addListSelectionListener(changeListener);
254     JScrollPane fontNameScroller = new JScrollPane(fontList);
255     fontBox.add(fontNameScroller);
256
257     chooser.add(fontBox);
258     chooser.add(Box.createHorizontalStrut(15));
259
260     Box styleBox = Box.createVerticalBox();
261     styleBox.add(new JLabel("Font Style"));
262     styleList = new JList(getStyleNames());
263     styleList.addListSelectionListener(changeListener);
264     JScrollPane styleScroller = new JScrollPane(styleList);
265     styleBox.add(styleScroller);
266
267     chooser.add(styleBox);
268     chooser.add(Box.createHorizontalStrut(15));
269
270     Box sizeBox = Box.createVerticalBox();
271     sizeBox.add(new JLabel("Size"));
272     sizeList = new JList(getSizeNames());
273     sizeList.addListSelectionListener(changeListener);
274     JScrollPane sizeScroller = new JScrollPane(sizeList);
275     sizeBox.add(sizeScroller);
276
277     chooser.add(sizeBox);
278
279     returnValue.add(chooser);
280     returnValue.setBorder(BorderFactory.createEtchedBorder());
281
282     return returnValue;
283   }
284
285   /**
286    * Creates the preview panel.
287    */

288   private Component createPreviewPanel(Font f, String JavaDoc previewText) {
289     previewTextArea = new JTextArea(previewText);
290     previewTextArea.setFont(f);
291     JPanel returnValue = new JPanel();
292     returnValue.add(previewTextArea);
293
294     returnValue.setBorder(BorderFactory.createEtchedBorder());
295     returnValue.setMinimumSize(new java.awt.Dimension JavaDoc(50,50));
296
297     return returnValue;
298   }
299
300   private Component createButtonPanel(ActionListener okListener, ActionListener cancelListener, JDialog newDialog) {
301     final JDialog dialog = newDialog;
302     JPanel returnValue = new JPanel();
303     returnValue.setLayout(new FlowLayout(FlowLayout.CENTER));
304
305     JButton okButton = new JButton("OK");
306
307     if (okListener != null)
308       okButton.addActionListener(okListener);
309
310     okButton.addActionListener(new ActionListener() {
311     public void actionPerformed(ActionEvent e) {
312       dialog.setVisible(false);
313     }
314       });
315
316     JButton cancelButton = new JButton("Cancel");
317     cancelButton.addActionListener(cancelListener);
318
319     cancelButton.addActionListener(new ActionListener() {
320     public void actionPerformed(ActionEvent e) {
321       dialog.setVisible(false);
322     }
323       });
324
325     JButton resetButton = new JButton("Reset");
326     resetButton.addActionListener(new ActionListener() {
327     public void actionPerformed(ActionEvent e) {
328       reset();
329     }
330       });
331
332     returnValue.add(okButton);
333     returnValue.add(resetButton);
334     returnValue.add(cancelButton);
335
336     getRootPane().setDefaultButton(okButton);
337
338     returnValue.setBorder(BorderFactory.createEtchedBorder());
339
340     return returnValue;
341   }
342
343   /**
344    * Resets the font to the original font.
345    */

346   public void reset() {
347     setFont(originalFont);
348   }
349
350   /**
351    * called when any of the JLists change.
352    */

353   protected void fontSelectionChanged() {
354     Font currentFont = previewTextArea.getFont();
355
356     String JavaDoc fontName = (String JavaDoc) fontList.getSelectedValue();
357     String JavaDoc styleString = (String JavaDoc) styleList.getSelectedValue();
358     String JavaDoc sizeString = (String JavaDoc) sizeList.getSelectedValue();
359
360     if (fontName == null || fontName.length() == 0) {
361       fontName = currentFont.getFontName();
362     }
363
364     int style = currentFont.getStyle();
365     if (styleString != null) {
366       if (styleString.equalsIgnoreCase("plain"))
367     style = Font.PLAIN;
368       else if (styleString.equalsIgnoreCase("bold"))
369     style = Font.BOLD;
370       else if (styleString.equalsIgnoreCase("italic"))
371     style = Font.ITALIC;
372       else if (styleString.equalsIgnoreCase("bold italic"))
373     style = Font.BOLD + Font.ITALIC;
374     }
375
376     int size = currentFont.getSize();
377     if (sizeString != null) {
378       try {
379     size = Integer.parseInt(sizeString);
380       } catch (Exception JavaDoc e) {
381       }
382     }
383
384     Font newFont = new Font(fontName, style, size);
385
386     previewTextArea.setFont(newFont);
387     SwingUtilities.windowForComponent(this).pack();
388   }
389
390   /**
391    * Gets all of the available font names.
392    */

393   private String JavaDoc[] getFontNames() {
394     return GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
395   }
396
397   /**
398    * Gets all of the available styles.
399    */

400   private String JavaDoc[] getStyleNames() {
401     return allowedFontStyles;
402   }
403
404   /**
405    * Gets all of the available sizes.
406    */

407   private String JavaDoc[] getSizeNames() {
408     return allowedFontSizes;
409   }
410
411   /**
412    * Gets the font selected by the chooser. if 'cancel' was pressed,
413    * then no font is selected.
414    */

415   public Font getSelectedFont() {
416     return selectedFont;
417   }
418
419   /**
420    * Sets the font selected by the chooser. this should be called when
421    * the 'ok' button is presed.
422    */

423   public void setSelectedFont(Font newFont) {
424     selectedFont = newFont;
425   }
426 }
427
Popular Tags