6

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!

Jumbala
  • 4,764
  • 9
  • 45
  • 65

2 Answers2

10

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);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • @Adam: did it work when you tried it? Again, I've not used it in this particular situation. – Hovercraft Full Of Eels Aug 23 '11 at 00:33
  • 1
    It works flawlessly! It seems a bit pixelized in my JLabel but I think that's how the font is made. Thanks again for the help! – Jumbala Aug 23 '11 at 00:35
  • 1
    Depending on context, `RendereringHints` may help. – trashgod Aug 23 '11 at 00:42
  • @trashgod I tried adding an anonymous inner class on the JLabel creation to override paintComponents and using Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); and it doesn't seem to change anything, any idea? – Jumbala Aug 23 '11 at 01:17
  • 1
    @Adam: perhaps the wrong antialiasing. Have you tried KEY_TEXT_ANTIALIASING and VALUE_TEXT_ANTIALIAS_ON? – Hovercraft Full Of Eels Aug 23 '11 at 01:19
  • @Hovercraft I just did and it doesn't work either... I'm going to keep trying other ways to make it look better and I'll come back when / if I find a way to make the text smoother – Jumbala Aug 23 '11 at 01:24
  • You can use `TextLayout`, shown [here](http://stackoverflow.com/questions/4285464/java2d-graphics-anti-aliased/4287269#4287269). – trashgod Aug 23 '11 at 07:23
1

I'd simply use:

Font.ITALIC

Font.BOLD

Font.PLAIN