Hexworks
Hexworks

Reputation: 534

How do I set custom fonts from css in JavaFX?

I have added a custom font to my project in the src/main/resources folder (RobotoMono.ttf). Then I try to load it from my css file like this:

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

but when I try to set this font to something it doesn't work:

.column-header-label {
    -fx-label-padding: 0;
    -fx-text-overrun: clip;
    -fx-font-family: 'RobotoMono';
}

If I set the font to something which is present on my system I can see that the font changes but the one included by me does not work.

What am I doing wrong?

Upvotes: 7

Views: 5625

Answers (3)

RonSiven
RonSiven

Reputation: 959

In your css, you have to specify a font-face with a url. Then, in your css element you have to use the name of the font from inside the ttf file, not the name of the font file itself. For instance, if you open the ttf file from Windows you see "Roboto Mono".

@font-face {
    src: url('RobotoMono.ttf');
}

.column-header-label {
    -fx-label-padding: 0;
    -fx-text-overrun: clip;
    -fx-font-family: 'Roboto Mono';
}

Upvotes: 8

parsa
parsa

Reputation: 995

just add the font to your java build path libraries for example in eclipse you have to right click on the project->properties->java build path->add JARs and then add your ttf font. after you have done this you need to just add the line below to your css

-fx-font-family: 'name of the font you have added to library without .tff';

make sure that your ttf font is inside the folder of your project

Upvotes: 1

Boris
Boris

Reputation: 24483

You declared where the font exists using the src property:

src: url('RobotoMono.ttf');

This is an instruction to look for RobotoMono.ttf in the same folder where the CSS file exists. If you created your JavaFX application using Maven, the style files should be in

src/main/resources/styles

So make sure the project's folder structure looks like:

Projects folder structure

Upvotes: 2

Related Questions