Using an external font in JavaFX CSS

Can you style a font with CSS in a JavaFX application? I have an FXML scene and corresponding CSS file. In Java code, you can set a font using the setFont method:

text.setFont(Font.loadFont("file:resources/fonts/SourceSansPro-Bold.ttf", 12));

I've tried various methods like this:

-fx-font-family: url("../fonts/SourceSansPro-Bold.ttf");

However, none of them seem to work.

Answer №1

My approach involves a mix of application code and CSS to apply styling using an external font.

In order to ensure the loadFont function is called early on in the application process, I place it within a customized Application init method.

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

When utilizing the font, I specify the font family in CSS as follows:

.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;
}

It's noteworthy that the CSS effectively adjusts the font sizes. Even though the font is initially loaded at size 10, it correctly conforms to the specified sizes in the CSS -fx-font-size declarations.

Applying inline styling to a label via CSS with a loaded Font during application initialization also functions seamlessly:

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

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

This response was retrieved from my contribution on a forum post regarding "Using Custom Fonts".

Answer №2

Almost there:

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

Give this a try, it should do the trick.


Maybe this suggestion will be useful? (I'm not JavaFX expert)


UPDATE:

Add your font:

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

Apply your font using -fx-:

-fx-font-family: 'Delicious';

Answer №3

Just discovered an interesting bit of information: If you're working with JavaFX-8 and need to incorporate both regular and bold versions of a font, you can define them using two separate @font-face declarations. This allows you to utilize the -fx-font-weight: bold; property.

@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;
}

Answer №4

One alternative method involves loading a font with FileInputStream instead of using CSS:

@FXML
private Label myLabel;

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

Font myFont = null;

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

myLabel.setFont(myFont);

}

Answer №5

Customizing Fonts in JavaFx Using CSS:

/* Importing custom fonts */
@font-face {
    font-family: "Roboto";
    font-style: normal;
    font-weight: 400;
    src: url("/fonts/Roboto-Regular.ttf");
}
@font-face {
    font-family: "Roboto Light";
    font-style: normal;
    font-weight: 300;
    src: url("/fonts/Roboto-Light.ttf");
}
@font-face {
    font-family: "Roboto Bold";
    font-style: normal;
    font-weight: 700;
    src: url("/fonts/Roboto-Bold.ttf");
}
@font-face {
    font-family: "Roboto ExtraBold";
    font-style: normal;
    font-weight: 900;
    src: url("/fonts/Roboto-ExtraBold.ttf");
}

/* Applying custom fonts to elements */

.title{
    -fx-font-size: 25px;
    -fx-font-family: "Roboto Light";
    -fx-font-weight: 300;
    -fx-text-fill: #333;
}

.subtitle{
    -fx-font-size: 18px;
    -fx-font-family: "Roboto Bold";
    -fx-font-weight: 700;
    -fx-text-fill: #333;
}

Answer №6

To successfully install the Font.ttf file, ensure it goes into the designated bin/<main application> directory along with your application's essential .class files. You can refer to this handy example image for guidance.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSS Duo-Toned Background

I've been searching everywhere for a solution to this issue. I have a design that I'm attempting to code using divs and CSS. The top half of the image features a gradient that transitions from left to right with different colors. My struggle lies ...

Is there an issue with the padding not functioning correctly on smaller and medium-sized devices when using Bootstrap

On my desktop, I added '50px' padding to the body of my page and it's working properly. However, on smaller and medium screens, it's not functioning correctly. I tried using Bootstrap @media CSS functionality, but it still doesn't ...

Guide on using JavaScript to implement the universal CSS selector

One technique I frequently employ is using the CSS universal selector to reset the dimensions in my HTML document: * { border: 0; margin: 0; padding: 0; } I wonder if a similar approach can be achieved with JavaScript as well? When it come ...

The smooth scroll feature is not functioning properly on the animated mouse-scroll down button

I've recently added an Animated Mouse Scroll Down button on my website. However, when I click the button, the smooth scroll feature is not working as expected. Important Note: I already have a separate button for navigating to the next section where ...

Align the UL in HTML to be on the same line as other spans

When examining this jsFiddle demonstration at the following link: http://jsfiddle.net/jrXwf/1/ The UL tag showcases a star rating, with accompanying text displayed on the line below it. Is there a method to have everything appear on a single line? Appre ...

The embed video is camouflaged within the bootstrap mobile display

I am currently using the latest version of bootstrap and bootswatch united theme to build and explore a standard website. The website is live at this link live site, featuring an embedded section on the right side as shown. My choice for the view engine is ...

Collecting data with Selenium as elements load [Python]

Is there a way to scrape only the newly generated items in sequence? I have a dynamic list that loads with scrolling. There are two methods I can use to scrape all generated divs: Scroll to the bottom of the list and then scrape all generated divs. Scroll ...

Utilizing pure CSS to target the first and last classes

I want to use pure CSS to select only the first and last classes throughout the entire document. In my scenario, the structure looks like this: <div class="Container"> <div> <div class="Parent"></div> <pre> ...

Tips for positioning label/input box/button on Internet Explorer 7

Here is a Fiddle example you can check out, along with the corresponding code : <div class="menu-alto"> <ul> <li> <a title="Link" href="#">Link</a> </li> <li class="newsletter ...

Can I use the mouseover event on an image to display a sibling div?

Hi everyone! I'm fairly new to web development and I could really use some advice. I'm trying to implement a mouseenter event on an img tag to show a sibling div, but I'm encountering some strange behavior. The mouseenter event seems to be w ...

Troubleshooting problems with printing HTML divs and page breaks caused by using float and position styles

Look at this class: .divDutySlip { width: 90mm; min-height: 120mm; padding: 2mm; /*float:left; position: relative; */ margin: 2mm; border: 1px solid #000000; page-break-inside: avoid; } I've modified two styles. Dis ...

Determine the selected radio button

----EDIT---- I am developing a jQuery mobile application and I need to determine which radio button is selected. This is the JavaScript code I'm using: function filter(){ if(document.getElementById('segment1').checked) { aler ...

Can CSS be used to automatically focus on a div element?

Can CSS be used to set autofocus on a div element? <div class="form-group" style="margin-left:10px"> <label for="organizationContainer" class="nmc-label">@Res.GroupStrings.CreateNewGroupOrganization</label> <div id="organiza ...

Implementing a click event on an image in an Angular 4 application

I'm facing an issue with adding a click event to an image within an Angular component. I have tried the following code: <img src="../../assets/add.svg" width="18" height="18" (click)="addItem()"> However, this approach does not seem to work as ...

Leveraging Template Variables for Styling in Vue 3's CSS Classes

Struggling to find the perfect way to utilize variables returned by Vue functions in CSS inline styles, specifically with the "width" style. I have two variables that are returned to the template and can be used with the {{}} syntax, but not directly as a ...

Having issues with customizing the design of MaterialUI Accordion header

Link to my code sandbox project I am encountering issues with the styling in my Accordion Heading. My Accordion Contents are set up like this: <Accordion heading1= { <DishItem name="Döner Teller Spezial" price="13,60€"/> ...

Steps for modifying an element in an array using Javascript

Currently, I am a beginner in the realm of JavaScript and I am trying to build a todo-style application. So far, I have successfully managed to create, display, and delete items from an array. However, I am facing challenges when it comes to editing these ...

duplicate styling for individual table cells

I am in need of a span element inside a td tag that I am generating within a table. In order to ensure the span fills the td, I have set it as an inline-block with a width and height of 100%. However, when pressing the delete key in the last cell, it star ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

"Enscroll – revolutionizing the way we scroll in

I recently incorporated the "enscroll" javascript scroll bar into my webpage. You can find more information about it at <div id="enscroll_name"> <ul> <li id="p1">product1</li> <li id="p2">product2</li> ...