Thor
Thor

Reputation: 19

How to load font in java?

I want to include a font called Fixedsys in my game and this is the code I use :

try{
    Font myFont = null;
    File fontFile = new File("Fixedsys.ttf");
    if(fontFile.exists()){
        myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);

        GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
        ge.registerFont(myFont);
        System.out.println("Not null");
    }else{
        System.out.println("FILE DOES NOT EXIST");
    }
} catch (FontFormatException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

For some reason, Java thinks the file DOES NOT exist and prints out the FILE DOES NOT EXIST line. I have searched through google and stackoverflow but none of then work when I use :

myComponent.setFont(myFont);

I get an error saying:

cannot find variable myFont

I have checked over and over and over but nothing seems wrong.

EDIT : I removed the if(file.exists()) line and i get a different error. I get :

Cannot read Fixedsys.ttf !

EDIT 2 : ug_'s comment proved right. Java was looking in the wrong folder for the file. Thanks.

Upvotes: 0

Views: 730

Answers (2)

david.pfx
david.pfx

Reputation: 10863

The real answer is that the font file does not exist at that path location. Look in Windows\Fonts or wherever the file really is.

Upvotes: 0

Kris Scheibe
Kris Scheibe

Reputation: 361

The myFont variable is a local variable inside the catch block and therefore doesn't exist anywhere else.

You have to make it a class variable to use it outside the catch block.

Like so:

class SomeClass {

   // declare here
   private Font myFont;

   public SomeClass() {

            try{
                // initialize here
                File fontFile = new File("Fixedsys.ttf");
                if(fontFile.exists()){
                myFont = Font.createFont(Font.TRUETYPE_FONT, fontFile).deriveFont(Font.PLAIN, 22f);

                GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
                ge.registerFont(myFont);
                System.out.println("Not null");
                }else{
                    System.out.println("FILE DOES NOT EXIST");
                }
            } catch (FontFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

   }

   // somewhere else:
   myComponent.setFont(myFont);

}

Upvotes: 2

Related Questions