Search code examples
cssjavafxfonts

Cannot applying custom font in JavaFX


Recently I'm developing a desktop application through javaFX, and I encountered a problem while trying adding custom fonts to text label.

I defined my custom font using @font-face in css, but it doesn't applied to the label, while -fx-text-fill worked properly.

My file directory

@font-face {
    font-family: 'LogoTypeGothic';
    src: url('../resources/fonts/LogoTypeGothic.otf');
}

.label {
    -fx-text-fill: #f6f6e9;
    -fx-font-family: "LogoTypeGothic";
}

I tried changing font to others that already exist like Comic Sans, and it works, meaning -fx-font-family can be changed.

.label {
    -fx-text-fill: #f6f6e9;
    /*-fx-font-family: "LogoTypeGothic";*/
    -fx-font-family: "Comic Sans MS";
}

My application

Here's my fxml code:

<children>
    <Label layoutX="92.0" layoutY="245.0" text="Username" />
    <Label layoutX="92.0" layoutY="292.0" prefHeight="20.0" prefWidth="58.0" text="Password" />
    <TextField layoutX="219.0" layoutY="241.0" prefHeight="23.0" prefWidth="134.0" />
    <PasswordField layoutX="219.0" layoutY="290.0" prefHeight="23.0" prefWidth="134.0" />
    <Button layoutX="146.0" layoutY="336.0" mnemonicParsing="false" prefHeight="39.0" prefWidth="137.0" text="Verify" />
</children>

Is there any method I missed? How to add my custom font into my javaFX application correctly?


Solution

  • Can you give a try by changing the path to below:

    @font-face {
        src: url('/fonts/LogoTypeGothic.otf');
    }
    

    If the above is not working, can you try the below one:

    @font-face {
        src: url('../../../fonts/LogoTypeGothic.otf');
    }
    

    I am not at the system right now to check this properly.

    UPDATE:

    I tried to check your code. Somehow I cannot make the first approach working, but the second one is working well with some fixes.

    The reason for the second approach not working with you, is because you are using the wrong -fx-font-family name. The font family may not always be the same as the file name. You need to open the file and check the font name declared in the file.

    enter image description here

    So below is the correct usage of your custom fonts.

    enter image description here

    @font-face {
        src: url("../../../fonts/MagarikadoGothic-Regular.otf");
    }
    
    @font-face {
        src: url("../../../fonts/LogoTypeGothic.otf");
    }
    
    .label1 {
        -fx-text-fill: #f6f6e9;
        -fx-font-family: "LOF Magarikado Gothic";
    }
    
    .label2 {
        -fx-text-fill: #f6f6e9;
        -fx-font-family: "07LogoTypeGothic7";
    }