108 lines
2.3 KiB
Java
108 lines
2.3 KiB
Java
package com.flaremicro.visualforecast.graphics;
|
|
|
|
import java.awt.Font;
|
|
import java.awt.FontFormatException;
|
|
import java.awt.Graphics;
|
|
import java.awt.image.BufferedImage;
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.net.URL;
|
|
import java.util.ArrayList;
|
|
import java.util.HashMap;
|
|
import java.util.List;
|
|
import java.util.Map;
|
|
|
|
public class FontManager {
|
|
private final Font baseFont;
|
|
private static FontManager instance = null;
|
|
|
|
private Map<URL, Integer> urlToFontMapping = new HashMap<URL, Integer>();
|
|
private List<Font> fonts = new ArrayList<Font>();
|
|
|
|
private FontManager() {
|
|
BufferedImage bufferedImage = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_BINARY);
|
|
Graphics g = bufferedImage.createGraphics();
|
|
baseFont = g.getFont();
|
|
g.dispose();
|
|
}
|
|
|
|
public static FontManager getInstance() {
|
|
if (instance == null)
|
|
{
|
|
instance = new FontManager();
|
|
}
|
|
return instance;
|
|
}
|
|
|
|
public Font getFont(int fontId){
|
|
if(fontId < 0 || fontId >= fonts.size())
|
|
return baseFont;
|
|
else return fonts.get(fontId);
|
|
}
|
|
|
|
public Font getFont(URL fontResource){
|
|
Integer i = urlToFontMapping.get(fontResource);
|
|
if(i == null)
|
|
return baseFont;
|
|
else return fonts.get(i);
|
|
}
|
|
|
|
public int getFontID(URL fontResource){
|
|
Integer i = urlToFontMapping.get(fontResource);
|
|
if(i == null)
|
|
return -1;
|
|
else return i;
|
|
}
|
|
|
|
public Font getOrCreateFont(int fontFormat, URL fontResource)
|
|
{
|
|
if(fontResource == null)
|
|
return baseFont.deriveFont(Font.PLAIN);
|
|
int i = getOrPrepareFont(fontFormat, fontResource);
|
|
return fonts.get(i);
|
|
}
|
|
|
|
public int getOrPrepareFont(int fontFormat, URL fontResource)
|
|
{
|
|
Integer i = urlToFontMapping.get(fontResource);
|
|
if(i == null)
|
|
{
|
|
Font f = baseFont.deriveFont(Font.PLAIN);
|
|
if(fontResource == null)
|
|
return -1;
|
|
InputStream stream = null;
|
|
try
|
|
{
|
|
stream = fontResource.openStream();
|
|
f = Font.createFont(fontFormat, stream);
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
catch (FontFormatException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
finally{
|
|
if(stream != null)
|
|
try
|
|
{
|
|
stream.close();
|
|
}
|
|
catch (IOException e)
|
|
{
|
|
e.printStackTrace();
|
|
}
|
|
}
|
|
synchronized(fonts)
|
|
{
|
|
i = fonts.size();
|
|
fonts.add(f);
|
|
urlToFontMapping.put(fontResource, i);
|
|
}
|
|
}
|
|
return i;
|
|
}
|
|
}
|