3

I want to load a font in a SWT. My ttf file is in the resources/fonts directory of my Maven project. I try to load it like this:

URL fontURL = MyClass.class.getResource("/fonts/myfont.ttf");
boolean fontLoaded = display.loadFont(fontURL.getPath());

But the resulting boolean is always false. I tried to prompt the result of fontURL.getPath(), and it is something like /C:/Users/myuser/Documents/.... If I copy this result in a String, remove the first / and try to call display.loadFont() with it, it works.

Another weird thing is that this is not the only resource I load this way. For example, this is how I load the icon of the window:

URL iconURL = MyClass.class.getResource("/images/myicon.png");
Image icon = new Image(display, iconURL.getPath());
shell.setImage(icon);

And it works fine. The only file posing problem is the font file. Does anybody know why ?

greg-449
  • 109,219
  • 232
  • 102
  • 145
Gaëtan
  • 779
  • 1
  • 8
  • 26
  • Note: Loading using a file path may work while you have things in separate files for testing but when you build a jar containing everything it will stop working because resources in a jar are not files and can't be addressed using a file path. Is this just an SWT app you are building or is it an Eclipse plug-in (which have a different way of loading resources)? – greg-449 Apr 03 '20 at 13:52
  • Don't worry, I know that. The build result is a zip containing, among others, the JAR and the resources. It is an SWT app that I am building. – Gaëtan Apr 03 '20 at 14:23

1 Answers1

2

The reason for / at the beginning is that getPath of the URL class returns the URL path defined by RFC 2396 (see javadocs).

As for why it's working for the Image constructor and not for loadFont() method, the answer can be found in the implementation. The constructor uses FileInputStream which internally normalizes the path, whereas loadFont() has a native implementation for loading which does not support such path.

Since in both cases a file path is expected, what you want to do is normalize the path yourself using either File constructor or Paths.get(url.toURI()).toString() method.

t3rmian
  • 641
  • 1
  • 7
  • 13