add .ttf file to java project

14,809

You can register the created font with the graphics environment , as below :

try {
   GraphicsEnvironment ge = 
     GraphicsEnvironment.getLocalGraphicsEnvironment();
 ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("akshar.TTF"));
} catch (IOException|FontFormatException e) {
 //Handle exception
}

Refer the Java tutorial.

Share:
14,809
newbee
Author by

newbee

Updated on June 04, 2022

Comments

  • newbee
    newbee almost 2 years

    I have downloaded akshar.ttf file and want to add it to my java project. I have tried the following ways by searching online but nothing worked so far.

    Try 1:

    Font ttfBase = null;
            Font ttfReal = null;
            try {
                InputStream myStream = new BufferedInputStream(new FileInputStream("akshar.TTF"));
                ttfBase = Font.createFont(Font.TRUETYPE_FONT, myStream);
                ttfReal = ttfBase.deriveFont(Font.PLAIN, 24);
            } catch (Exception ex) {
                ex.printStackTrace();
                System.err.println("akshar font not loaded.");
            }
    

    Try 2:

    Font font = new Font("akshar",Font.PLAIN,15);
    

    I have the akshar.ttf file at the following places:-

    1. java/jre/lib/fonts
    2. bin folder of my project
    3. src folder of my project

    I am new to java and have tried all these by following various links online. Please help me where am i going wrong.

  • Andrew Thompson
    Andrew Thompson about 11 years
    Good point. See also this example & this example.
  • newbee
    newbee about 11 years
    @Noob UnChained : I'm getting this error message java.io.IOException: Can't read akshar.ttf at java.awt.Font.createFont(Unknown Source)
  • AllTooSir
    AllTooSir about 11 years
    Check the path and filename of the .ttf file , make sure it is correct !
  • newbee
    newbee about 11 years
    @NoobUnChained what is the correct place for placing the ttf file?