How to set a custom font's size and other attributes (bold, italic, etc) in Java SWING

Adam Smith picture Adam Smith · Aug 23, 2011 · Viewed 7.7k times · Source

Usually, when I initialize the fonts I want to use in my SWING applications, I do it this way:

public static final Font TITLEFONT = new Font("Calibri", Font.BOLD, 40);

Now, I have to do it a bit differently since I'm using some custom fonts from a .ttf file. I initialize the font this way:

try
{
    InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
    TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is);
}
catch (Exception ex)
{
    ex.printStackTrace();
    System.err.println("Font not loaded.  Using Calibri font.");
    TITLEFONT = new Font("Calibri", Font.BOLD, 40);
}

I'm pretty sure it initializes it correctly (I can't tell for sure since it is too small for me to see), but I'd like to know how I can manually set the font's size (and if it's bold / other attributes) when loading a font this way.

Thanks a lot in advance!

Answer

Hovercraft Full Of Eels picture Hovercraft Full Of Eels · Aug 23, 2011

createFont returns a Font and you can call deriveFont(...) on this, passing in a float for the point size, or an int and float for Font style and point size. I cannot say whether it will work for your particular situation, but it's worth a try.

e.g.,

InputStream is = OptionsValues.class.getResourceAsStream("fonts//KOMIKAX_.ttf");
TITLEFONT = Font.createFont(Font.TRUETYPE_FONT, is).deriveFont(Font.BOLD, 40f);