arun
arun

Reputation: 368

JavaFX Custom Font

How to set a custom font to JavaFX (Java 17, OpenJFX)? I tried copying files to the resources/fonts folder and importing them via @font-face in CSS. It didn't work. Also tried @import - no use.

Upvotes: 2

Views: 921

Answers (1)

arun
arun

Reputation: 368

After searching the internet for hours, finally resolved how to set the custom font in JavaFX and use it comfortably within the CSS.

The CSS File looks like this:

@font-face
{
    -fx-font-family: "Quicksand Light";
    src: url("../fonts/Quicksand-Light.ttf");
}


@font-face
{
    -fx-font-family: "Quicksand Regular";
    src: url("../fonts/Quicksand-Regular.ttf");
}

@font-face
{
    -fx-font-family: "Quicksand Medium";
    src: url("../fonts/Quicksand-Medium.ttf");
}

@font-face
{
    -fx-font-family: "Quicksand Semi-bold";
    src: url("../fonts/Quicksand-SemiBold.ttf");
}

@font-face
{
    -fx-font-family: "Quicksand Bold";
    src: url("../fonts/Quicksand-Bold.ttf");
}

.light
{
    -fx-font-family: "Quicksand Light";
}

.regular
{
    -fx-font-family: "Quicksand Regular";
}

.medium
{
    -fx-font-family: "Quicksand Medium";
}

.semi
{
    -fx-font-family: "Quicksand Semi-bold";
}

.bold
{
    -fx-font-family: "Quicksand Bold";
}

Now, in your java class you can set the styles accordingly as below:

    Label lblThin = new Label("Light");
    lblThin.getStyleClass().add("light");

    Label lblRegular = new Label("Regular");
    lblRegular.getStyleClass().add("regular");

    Label lblMedium = new Label("Medium");
    lblMedium.getStyleClass().add("medium");

    Label lblSemiBold = new Label("Semi Bold");
    lblSemiBold.getStyleClass().add("semi");

    Label lblBold = new Label("Bold");
    lblBold.getStyleClass().add("bold");

Two main things to note:

  1. The font name should be exactly as per the font file and in double quotes
  2. The original filename of the font should be maintained in your resources

Attaching the resources/fonts photo to make it easy to understand:

enter image description here

Output:

enter image description here

I hope this saves someone's time.

Upvotes: 3

Related Questions