Reputation: 71
For some reason I am unable to load any TTF fonts in my app. Here is a simple example:
File f = new File("/blah/font.ttf");
System.out.println(f.canRead());
System.out.println(f.length());
System.out.println(Font.loadFont(new FileInputStream(f), 20));
The output:
true
52168
null
The font is not loaded. I tried different fonts, but none of them worked. What could be the problem? I'm running Arch Linux.
$ java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
Upvotes: 1
Views: 2156
Reputation: 4803
Assuming you have a package structure in your application like this
The following code should work
import java.io.InputStream;
import javafx.scene.text.Font;
public class AccessTest {
public static void main(String[] args) throws URISyntaxException, MalformedURLException {
InputStream is = AccessTest.class.getResourceAsStream("OpenSans-Regular.ttf");
Font font = Font.loadFont(is, 12.0);
System.out.println("Font: " +font);
File f = new File(AccessTest.class.getResource("OpenSans-Regular.ttf").toURI());
// should not be used because of f.toURL() is deprecated
Font font1 = Font.loadFont(f.toURL().toExternalForm(), 12.0);
System.out.println("Font 1: " + font1);
Font font2 = Font.loadFont(f.toURI().toURL().toExternalForm(), 12.0);
System.out.println("Font 2: " + font2);
}
}
This gives me the following output:
Font: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 1: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
Font 2: Font[name=Open Sans, family=Open Sans, style=Regular, size=12.0]
If you put the font file outside of your package there could be an access violation. In your case the Font.load() method simply breaks in construction a suitable Inputstream. It could be a bit tricky to get the suitable URL or URI that the load method uses.
Upvotes: 1