Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set custom fonts from css in JavaFX?

Tags:

css

fonts

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?

like image 617
Hexworks Avatar asked Feb 05 '18 11:02

Hexworks


People also ask

How do I link CSS to JavaFX?

In the Properties tab, under the 'JavaFX CSS' section, click on the 'Stylesheets' option. Select the CSS file, and that's it.

Can you use CSS in JavaFX?

This topic describes how to use cascading style sheets (CSS) with JavaFX applications. Use CSS to create a custom look for your application. Style sheets contain style definitions that control the look of user interface elements. Using CSS in JavaFX applications is similar to using CSS in HTML.

Does CSS allow custom fonts?

html , then open styles. css in your text editor. You can use the @font-face rule to load a custom font on a web page.


2 Answers

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';
}
like image 191
RonSiven Avatar answered Sep 23 '22 01:09

RonSiven


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

like image 45
Boris Avatar answered Sep 21 '22 01:09

Boris