23 January 2013

Add custom font to a Java Swing application


After a couple of tryouts and failure, I’ve finally found a way to add custom fonts to a small Java Swing application I was developing for a school assignment.

wp4

There are several ways to accomplish this, yet for me, the following code is the first thing that actually worked:

Font myFont = null;
File fontFile = new File("path/to/font.ttf");
myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);
	
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);	

The first three lines of code declare a variable of type Font, we use File to upload the font file we want to use with our application and create the font. The deriveFont(Font.PLAIN, 22f); part is what gives the font an overall style. I haven’t played much with this function yet.

The last two lines of code:

GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(myFont);	

Are what actually register the font so it is usable. Finally:

yourComponent.setFont(myFont);

Will use the custom font on the Swing component you want.



Last updated on
Fonts, Java, Programming, Typography


Related Articles



Leave a response

Fields marked with * are required. Email addresses are never shared.



// //