0

In a folder called data, I have a font file called font.ttf.

I want to read it in, like this:

try {
   Font f = Font.createFont(Font.TRUETYPE_FONT, 
      new File("data/font.ttf")).deriveFont(12.0);
} catch (IOException | FontFormatException e) {}

That worked fine up until I removed the same font from the system (it's still in the data folder!). Now, it's just showing Java's generic font.

Is it even possible to read in a font from a file which is not in the System Fonts folder?

log_0
  • 838
  • 2
  • 7
  • 17
  • That code will not compile. Please edit your question to show your actual code, including the `catch` block(s) which handle IOException and FontFormatException. – VGR Apr 01 '15 at 17:07
  • OK, added the catch block. – log_0 Apr 01 '15 at 17:17
  • And is an exception actually occurring? I suggest you replace that println with `throw new RuntimeException(e);`. Unless you really want your application to run without having loaded your font. – VGR Apr 01 '15 at 17:31
  • It's not throwing any exception. That's strange as the font file is actually there. And that "referring to a file" thing works if the font is actually installed on the system. – log_0 Apr 01 '15 at 17:35
  • Solved by using a GraphicsEnvironment (see http://stackoverflow.com/questions/13717481/setting-custom-font) – log_0 Apr 01 '15 at 18:11
  • What you really mean is, you had to register the font after loading it. Correct? – VGR Apr 01 '15 at 18:19
  • Exactly, it had to be registered. – log_0 Apr 03 '15 at 14:50

1 Answers1

0

You don't seem to be doing anything with that Font f once you've loaded it in, so you might simply be losing it due to block scoping.

Font fallback = load some system default;
Font myfont = null;

...

try {
  File ffile = new File("data/font.ttf");
  myfont = Font.createFont(Font.TRUETYPE_FONT, ffile).deriveFont(12);
} catch (FontFormatException ffe) {
  System.out.println("Tried to load a bad font...");
  ffe.printStackTrace();
} catch (IOException ioe) {
  System.out.println("I have no idea what went wrong");
  ioe.printStackTrace();
} finally {
  loadMyApplication(myfont == null ? fallback : myfont);
}

Or if you absolutely need that font for correct UI building or content rendering, call loadMyApplication in the try block, so that any catches prevent your application from loading.

Mike 'Pomax' Kamermans
  • 49,297
  • 16
  • 112
  • 153