Specifying external font in JavaFX CSS

Another way is to load font using FileIUnputStream, thus you don't need to use css:

 @FXML
    private Label myLabel;

@Override
    public void initialize(URL arg0, ResourceBundle arg1){

Font myFont = null;

        try {
            myFont = Font.loadFont(new FileInputStream(new File("patch_to_font.ttf")), 10);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        myLabel.setFont(myFont);

}

I use a combination of application code and CSS to style via an external font.

I place the loadFont call inside an overridden Application init method to make sure it is invoked before anything much happened in the application.

Font.loadFont(CustomFontTest.class.getResource("TRON.TTF").toExternalForm(), 10);

To use the font, I reference the font by font family in CSS:

.menu-bar {
    -fx-background-color: transparent;
    -fx-font-family: TRON;
    -fx-font-size: 40px;
}

.context-menu {
    -fx-font-family: TRON;
    -fx-background-color: transparent;
    -fx-font-size: 12px;
}

Nice that the CSS sizes the fonts fine. Even when the font is loaded at size 10, the font was resized correctly to what is specified in the CSS -fx-font-size specifications.

Inline styling of a label via CSS using a Font loaded during application initialization also works fine:

Label testControl = new Label("TRON");
testControl.setStyle("-fx-font-family: TRON; -fx-font-size: 120;");

The TRON font was downloaded from dafont and placed in the same directory as the CustomFontTest class and copied to the build output directory by the build system.

Answer copied from my answer to a forum post on "Using Custom Fonts".


Just found out one more detail: In JavaFX-8 if you want to have regular and bold variants of the same font you can specify them with two instances of @font-face. Then you can use -fx-font-weight: bold;

@font-face {
    font-family: 'Droid Sans';
    src: url('DroidSans.ttf');
}

@font-face {
    font-family: 'Droid Sans Bold';
    src: url('DroidSans-Bold.ttf');
}

.root {
    -fx-font-family: 'Droid Sans'; 
}

.table-row-cell:focused .text {
    -fx-font-weight: bold;
}

You were close to the solution:

-fx-font-family: 'Helvetica', Arial, sans-serif;

Try this, it should work fine.


Maybe this could help? (I'm not an expert in JavaFX)

https://forums.oracle.com/forums/thread.jspa?messageID=10107625


EDIT:

Load your font:

@font-face {
    font-family: Delicious;
    src: url('Delicious-Roman.otf');
}

Use your font with -fx-:

-fx-font-family: 'Delicious';

Tags:

Css

Fonts

Javafx