nus-cs2103-AY2425S1 / forum

11 stars 0 forks source link

💡 Custom/External Fonts in JavaFX via CSS #275

Open Zeepheru opened 2 months ago

Zeepheru commented 2 months ago

Was pretty frustrating to figure out, with ChatGPT + Internet searches giving confusing contradicting info, so here's what worked for me if anyone wants to know:


1. Get your font files

Generally of the filetypes .otf or .ttf. Create a new folder fonts in your src/main/resources directory. Place the files there.

image

2. Load fonts

In your Main class, or whatever extends Application and is where your GUI runs from, import

import javafx.scene.text.Font;

And add the following in the constructor:

Font.loadFont(getClass().getResourceAsStream("/fonts/<font-filename>"), v);

3. Add fonts to CSS

Whenever you specify a font in CSS, simply replace that string with the name of the font you have loaded.

.button {
    ...
    -fx-font: bold 16px "Comic Sans MS";
    ...
}

.text-field {
    ...
    -fx-font-family: "Montserrat SemiBold";
    ...
}

Note:

You might want to check the exact name of the font, since it can be different from the filename of that font. Make sure in the CSS sheet you use the actual name (e.g. Montserrat SemiBold or Comic Sans MS) and not the filename (Montserrat-SemiBold or comic).

You can obtain the names by:

Font font1 = Font.loadFont(getClass().getResourceAsStream("/fonts/Inter-Medium.ttf"), 18); // load font from file
font1.getName(); // gets you name of the font

Voila!

You can now show off to the world your teammates your excellent taste in font choice.

image

uniqly commented 2 months ago

Another way to get the font name (at least on Windows) without using code is by:

  1. Right click on the font file (.otf/.ttf/etc) in file explorer
  2. Go to Details tab
  3. Look for the Title row in the Property column and the name should be in the Value column on the same row.

Alternatively, you can just open the font file (double click) and then the name should be on the top at Font name: {font name}.