Sunday, February 11, 2018

How to use google fonts in JavaFX

There are some resources on internet but not all of them works for me. Following method works for me. Here is my step-by-step guide. Google fonts are at https://fonts.google.com. I wasn't able to download fonts directly from this site, I didn't found link to download. luckily there is a github repository where are all fonts available to download. It's at https://github.com/google/fonts/

Download font

Get font and download it to you project at src/main/resources/font/.

Make font available in JavaFX

Now I have to tell JavaFX something like look at there is new font called 'Cardo'. It could be done by static method loadFont on javafx.scene.text.Font class.

Here is a example:

Font f = Font.loadFont(Main.class.getResource("/font/Cardo-Regular.ttf").toExternalForm(), 12);

Use font in UI

Defined font could be used from css file and directly from java code.

from css

Font can be used from css file like this:

final Scene scene = new Scene();
scene.getStylesheets().add("gui/myStyle.css");
And than set all text in application to new font:
.root {
  -fx-font-family: Cardo;
}

From java FX code

Following code write to give Graphics object text black "Hello world":

graphics.setFont(f);
graphics.setTextAlign(TextAlignment.CENTER);
graphics.setTextBaseline(VPos.CENTER);
graphics.setFill(Color.BLACK);
graphics.fillText("Hello world", 100, 50);

No comments:

Post a Comment