View Javadoc

1   /*
2    *  File: FontManager.java 
3    *  Copyright (c) 2004-2007  Peter Kliem (Peter.Kliem@jaret.de)
4    *  A commercial license is available, see http://www.jaret.de.
5    *
6    * All rights reserved. This program and the accompanying materials
7    * are made available under the terms of the Common Public License v1.0
8    * which accompanies this distribution, and is available at
9    * http://www.eclipse.org/legal/cpl-v10.html
10   */
11  package de.jaret.util.swt;
12  
13  import java.util.HashMap;
14  import java.util.Map;
15  
16  import org.eclipse.swt.graphics.Device;
17  import org.eclipse.swt.graphics.Font;
18  import org.eclipse.swt.graphics.FontData;
19  import org.eclipse.swt.widgets.Display;
20  
21  /**
22   * Simple class to collect allocated fonts and to relese them.
23   * 
24   * @author Peter Kliem
25   * @version $Id: FontManager.java 242 2007-02-11 21:05:07Z olk $
26   */
27  public class FontManager {
28      protected static Map<Device, FontManager> _instances = new HashMap<Device, FontManager>();
29  
30      protected Map<FontData, Font> _fontTable = new HashMap<FontData, Font>(10);
31      protected Device _device;
32  
33      public FontManager(Device device) {
34          if (device != null) {
35              _device = device;
36          } else {
37              _device = Display.getCurrent();
38          }
39      }
40  
41      public static FontManager getFontManager(Device device) {
42          FontManager cm = _instances.get(device);
43          if (cm == null) {
44              cm = new FontManager(device);
45              _instances.put(device, cm);
46          }
47          return cm;
48      }
49  
50      public static void disposeAll() {
51          for (Device device : _instances.keySet()) {
52              FontManager cm = getFontManager(device);
53              cm.dispose();
54          }
55          _instances.clear();
56      }
57  
58      public void dispose() {
59          for (Font Font : _fontTable.values()) {
60              Font.dispose();
61          }
62      }
63  
64      public Font getFont(FontData FontData) {
65          Font Font = _fontTable.get(FontData);
66          if (Font == null) {
67              Font = new Font(_device, FontData);
68              _fontTable.put(FontData, Font);
69          }
70          return Font;
71      }
72  }