How to add a custom font family to FlatLaf for a Java Swing application

736 Views Asked by At

I'm trying to change the Font Family with FlatLaf for a Java Swing application. It would be cool to find a way to change it in the customized theme files (mytheme.properties) for FlatLaf. I saw on the FlatLaf docs that its possible to specify font families.

From FlatLaf doc:

family[, family ...] specify one or more font families. If a family is not available, then the next family is used. If none of the families are available, the family of the default/base font is used. If a family name contains spaces, enclose it in " or '.

Example:

defaultFont = 13 "Open Sans", "Noto Sans", Roboto, Arial

I want to download a font family, add the .ttf file to my project, and specify the font family via the .properties file of FlatLaf.

1

There are 1 best solutions below

0
creme332 On

Here's how I set the default font of my Maven project to Poppins Black, based on the comment by Joachim.

I placed my downloaded font file Poppins-Black.ttf inside resources/font folder. Maven will look for my font inside the resources folder.

Then, I loaded my Poppins-Black.ttf file and then I registered it as a font:

File font_file = new File(this.getClass().getResource("/font/Poppins/Poppins-Black.ttf").getPath());
Black = Font.createFont(Font.TRUETYPE_FONT, font_file);  
GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(Black);

Important note:

  • If you are not using Maven your method of loading the font file might be slightly different.
  • The above piece of code must be executed before setting up the look and feel of your application.

In my .properties file, I can now use "Poppins Black" to refer to the new font:

defaultFont = 18 "Poppins Black"

Now the default font of my application will be set to Poppins Black.

References