Jump to content
  • Advertisement

Yar

Sign in to follow this  
  • entries
    208
  • comments
    383
  • views
    66063

TTF Font Loader

Sign in to follow this  
H_o_p_s

391 views

import	java.awt.Component;
import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.io.InputStream;
import java.net.URL;

public class FontLoader {

private static boolean SHOW_DEBUG = true;

public static void setFont(Component c, String filename, int fontsize) {
try {
URL url = c.getClass().getClassLoader().getResource(filename);
InputStream in = url.openStream();
if(SHOW_DEBUG)
System.out.println("FontLoader: Creating font from stream...");
Font font = Font.createFont(Font.TRUETYPE_FONT, in);
if(SHOW_DEBUG)
System.out.println("FontLoader: Setting Font Size...");
Font cFont = new Font(font.getName(), Font.PLAIN, fontsize);
in.close();
c.setFont(cFont);
if(SHOW_DEBUG)
System.out.println("FontLoader: Loaded font: "+font.getName()+" at size "+fontsize);
} catch (java.io.IOException e) {
if(SHOW_DEBUG)
System.out.println("FontLoader: IOEException with"+filename);
} catch (java.awt.FontFormatException eb) {
if(SHOW_DEBUG)
System.out.println("FontLoader: Font Format Exception");
}
}
}



This class with load a TTF file to any Component (such as a Frame or Button). It also has some error handling so you know what went wrong when it doesn't change the font. The most common error is incorrect path to the TTF file...

Anyway, Enjoy!
Sign in to follow this  


2 Comments


Recommended Comments

I didn't know it was possible!

The boolean and the "if(SHOW_DEBUG) blah" is ugly, why don't you use logging?

Share this comment


Link to comment
The version that I'm using is connected into my Log object, but I felt that it would be more usable to people if they didn't have to go through all of my specific coding.

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!