3

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.

newbee
  • 409
  • 2
  • 12
  • 34
  • If it is in the `src` folder it should make its way into the `bin` folder automatically, shouldn't it? The `Font` will need to be accessed by `URL` rather than `File`. Check the [embedded-resource info. page](http://stackoverflow.com/tags/embedded-resource/info) for how to gain the URL. – Andrew Thompson Apr 29 '13 at 14:34
  • is it present in the same folder as your check class? The third try should work then; at least the `InputStream` object shouldn't be null. – Abdullah Shoaib Apr 29 '13 at 14:35
  • As the font is part of the application (could be packed in a jar), do not use File but a resource: `getClass().getResourceAsStream("/akshar.TTF")`. Mind that is *case-sensitive*! – Joop Eggen Apr 29 '13 at 14:43

2 Answers2

7

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.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • Good point. See also [this example](http://stackoverflow.com/questions/6965038/getting-fonts-sizes-bold-etc/6965149#6965149) & [this example](http://stackoverflow.com/a/8365030/418556). – Andrew Thompson Apr 29 '13 at 14:38
  • @Noob UnChained : I'm getting this error message `java.io.IOException: Can't read akshar.ttf at java.awt.Font.createFont(Unknown Source)` – newbee Apr 29 '13 at 14:44
  • Check the path and filename of the .ttf file , make sure it is correct ! – AllTooSir Apr 29 '13 at 14:45
  • @NoobUnChained what is the correct place for placing the ttf file? – newbee Apr 29 '13 at 15:00
-1

Put your ttf into the assests folder :)

Theresa Gamit
  • 292
  • 1
  • 4
  • 14