Subscribe to Dogstopper's Code Mania        RSS Feed
-----

Font Madness

Icon 1 Comments
So, while programming my most recent game, I encountered several issues which just absolutely drove me insane - I wanted to use a custom font in my game. This is one that is not natively found on any machine, so I had a little predicament. Well, after doing some searching through the API, I stumbled upon the createFont() method. Well, I run this inside of a jar file and so, after a bit of difficulty, managed to load the font.

However, since it is a pain to redo fonts every time you need them, I made a class with static loader methods (to load and return images, fonts, ...). After calling that method, I could manipulate fonts normally. For those of you who don't know, you load fonts like this:
Font font = new Font("Arial", Font.PLAIN, 28);



Where the first parameter is the font name, the second is the style constant, and the last parameter is the size (in point size, not pixels). The 3 main Font style constants are Font.PLAIN, Font.BOLD, and Font.ITALIC.

So, let me familiarize you with the createFont() and deriveFont() methods. createFont() takes 2 parameters, one is a filetype constant (Almost always Font.TRUETYPE_FONT) and the second is either a File object or an InputStream object. I used the latter since I am using jar files. So now, the method I created creates a new font.

deriveFont() has five variations, but the three that you should know are deriveFont(int), deriveFont(float) and deriveFont(int, float). The int is one of the style constants that I gave above and teh float is the point size (e.g 28f).

Here is the method.
	public static Font loadFont(float size, int style, JPanel jp) {
                // Opens the JPanel's resource called font/chem1.ttf
		InputStream is = jp.getClass().getResourceAsStream("fonts/chem1.ttf");
	        Font font = null;
		try {
			font = Font.createFont(Font.TRUETYPE_FONT, is);
			font = font.deriveFont(size);
			font = font.deriveFont(style);
		} catch (FontFormatException e) {
                        System.err.println("Font is null");
                        System.exit(1);
		} catch (IOException e) {
                        System.err.println("Font is null");
                        System.exit(1);
		}
		
                // CAREFUL, if font returns null, you can have NullPointerExceptions
		return font;
	}



Now that we have this class setup, we can load a font like so:
		font = Loader.loadFont(36f, Font.BOLD, myJPanelObj);



And as a final note, don't forget deriveFont(). It's very useful for changing fonts without recreating the resource!

:)

1 Comments On This Entry

Page 1 of 1

WolfCoder 

08 March 2010 - 08:58 AM
This reminds me why I don't write games in JAVA.
0
Page 1 of 1

December 2018

S M T W T F S
      1
2345678
91011121314 15
16171819202122
23242526272829
3031     

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)