Search code examples
javafontsgraphics2dtruetype

How to load and use ttf font from jar


Trying to write a class:

private void gameLevel(Graphics g) {
  try {
     InputStream fnt_stream = getClass().getResourceAsStream("resources/iomanoid.ttf");
     Font myFont = Font.createFont(Font.TRUETYPE_FONT, fnt_stream);
     Font Iomanoid = new Font("Iomanoid", Font.BOLD, 40);

     String msg = "Level";
     g.setColor(Color.black);
     g.setFont(Iomanoid);
     g.drawString(msg, 111,111);
  } catch (Exception ex) {
     System.out.println(ex);
  }

The message appears, but not with the font specified.


Solution

  • Beside other comments

    replace

    Font Iomanoid = new Font("Iomanoid", Font.BOLD, 40);
    

    by

    Font iomanoid = myFont.deriveFont(Font.BOLD, 40f);
    

    this font needs afterwards to be registered (as mentioned by mushfek0001)

    For more information about fonts have a look at the Oracle tutorial about Physical and Logical Fonts