I need to use custom fonts (ttf) in my Java Swing application. How do I add them to my package and use them?
Mean while, I just install them in windows and then I use them, but I don't wish that the usage of the application will be so complicated, it`s not very convenient to tell the user to install fonts before using my application.
you would run your program with from the My_Program directory with java bin/prog . Then in your code the file path and name to pass to either the InputStream or File would be "Fonts/TestFont. ttf" .
To add your own font to your JDK 1.1 Runtime, you need to create a charset converter and specify it in the font. properties file . The following example illustrates how to add your own platform font to the Java serif font. In this example, your font contains 256 glyphs, which are indexed 0 - 0xff.
This can be done easily in Eclipse, by going to menu Window > Preferences… In the Preferences dialog: Select General > Appearance > Colorsand Fonts (1) in the left pane. Select Java Editor Text Font (2) in the center.
You could load them via an InputStream
:
InputStream is = MyClass.class.getResourceAsStream("TestFont.ttf");
Font font = Font.createFont(Font.TRUETYPE_FONT, is);
This loaded font has no predefined font settings so to use, you would have to do:
Font sizedFont = font.deriveFont(12f);
myLabel.setFont(sizedFont);
See:
Physical and Logical Fonts
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With