28

Firstly, I am quite a new guy in coding. I need to embed a font in my java FXML-based app and don't know how to do it. I have pasted the font, fontName.ttf in a "resources" folder in the root of the sources of my project, ie App/src/app/resources. I have set the CSS for the component (text) as

#text {
    -fx-font-family: url(resources/fontName.ttf);
}

I have also tried adding inverted commas in the url, ie url("resources/fontName.ttf");, but it doesn't work. I have also set the CSS id for the component, so that can't be the problem. Is there any other working way to do so? I have seen http://fxexperience.com/2010/05/how-to-embed-fonts/, but it doesn't work since I have JDK 1.7 u21. Any ideas for a correct way to embed fonts?

2 Answers 2

48

Solution Approach

I updated the sample from Javafx How to display custom font in webview? to demonstrate using a custom true-type font in JavaFX controls styled using CSS.

Key points are:

  1. Place the font in the same location as your application class and ensure your build system places it in your binary build package (e.g. application jar file).
  2. Load the code font in your JavaFX code before you apply a style which uses it. Font.loadFont(CustomFontApp.class.getResource("TRON.TTF").toExternalForm(), 10);
  3. To use the custom font in a style class use the -fx-font-family css attribute and just reference the name of the font (e.g. in this case "TRON").
  4. Create and load a stylesheet which defines the style classes.
  5. Apply style classes to your controls.

Additional Information

If you are using Java 8, you may be interested in Use web(Google) fonts in JavaFX.

Font Collections

If your font file is in .ttc format, containing multiple fonts in a single file, then use the Font.loadFonts API (instead of Font.loadFont). Note that Font.loadFonts is only available since JDK 9 and is not available in earlier releases.

Sample Output Using a Custom Font

tronfonts

Sample Code

The example relies on a TRON.TTF font which you can download from dafont.

CustomFontApp.java

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.image.*;
import javafx.scene.layout.VBox;
import javafx.scene.text.*;
import javafx.stage.Stage;

// demonstrates the use of a custom font.
public class CustomFontApp extends Application {
  public static void main(String[] args) { launch(args); }
  @Override public void start(Stage stage) {
    stage.setTitle("TRON Synopsis");

    // load the tron font.
    Font.loadFont(
      CustomFontApp.class.getResource("TRON.TTF").toExternalForm(), 
      10
    );

    Label title = new Label("TRON");
    title.getStyleClass().add("title");

    Label caption = new Label("A sci-fi flick set in an alternate reality.");
    caption.getStyleClass().add("caption");
    caption.setMaxWidth(220);
    caption.setWrapText(true);
    caption.setTextAlignment(TextAlignment.CENTER);

    VBox layout = new VBox(10);
    layout.setStyle("-fx-padding: 20px; -fx-background-color: silver");
    layout.setAlignment(Pos.CENTER);
    layout.getChildren().setAll(
      title,
      new ImageView(
        new Image(
          "http://ia.media-imdb.com/images/M/MV5BMTY5NjM2MjAwOV5BMl5BanBnXkFtZTYwMTgyMzA5.V1.SY317.jpg"
        )
      ),
      caption
    );

    // layout the scene.
    final Scene scene = new Scene(layout);
    scene.getStylesheets().add(getClass().getResource("custom-font-styles.css").toExternalForm());
    stage.setScene(scene);
    stage.show();
  }
}

custom-font-styles.css

/** file: custom-font-styles.css
 * Place in same directory as CustomFontApp.java 
 */

.title {
    -fx-font-family: "TRON";
    -fx-font-size: 20;
}

.caption {
    -fx-font-family: "TRON";
    -fx-font-size: 10;
}

On FXML Usage

Font.loadFont(url, size) is a static method taking two parameters. I don't think you can invoke font.loadFont from FXML and wouldn't advise it if you could. Instead, load the font in Java code (as I have done in my answer) before you load your FXML or style sheet which requires the font.

9
  • Error comes up and says can't find symbol: loadFont in class Font. Three identifiers are expected. (I imported font in fxml as import javafx.scene.text.Font;) Jun 1, 2013 at 6:12
  • 1
    Added a section on FXML usage to the answer.
    – jewelsea
    Jun 1, 2013 at 7:17
  • Error comes up. See it here: docs.google.com/document/d/… Jun 1, 2013 at 7:40
  • I can't reproduce your error - the solution in my answer works for me. You will need to post an sscce which replicates your error if you wish to receive further assistance.
    – jewelsea
    Jun 1, 2013 at 7:46
  • Guess the error was with other code logic. Sorry if I wasted ur time, but thanks for telling the answer Jun 1, 2013 at 7:58
21

I know you didn't ask for a pure programmatic way to use a custom TTF font in a java fx application but i thought maybe it helps someone to see a programmatic version:

public class Test2 extends Application {

  public static void main(String[] args) {
    launch(args);
  }

  public void start(final Stage primaryStage) {
    Group rootGroup = new Group();

    // create a label to show some text
    Label label = new Label("Demo Text");
    try { 
      // load a custom font from a specific location (change path!)
      // 12 is the size to use
      final Font f = Font.loadFont(new FileInputStream(new File("./myFonts/TRON.TTF")), 12);
      label.setFont(f); // use this font with our label
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    rootGroup.getChildren().add(label); 

    // create scene, add root group and show stage
    Scene scene = new Scene(rootGroup, 640, 480, Color.WHITE);
    primaryStage.setScene(scene);
    primaryStage.show();
  }
}

That did the job for me. You can place the font wherever you want just make sure you adapt the path.

You can find a lot more about using fonts inside java fx apps here.

HTH

1
  • Its almost 2022 (Dec 14th 2021) at the time of writing this, and it seems to me, some of the methods that use to work for loading fonts in JavaFX, no longer work. This worked for me, so thank you @Chris (+1up 🍄) Heya, its a me, Mario!
    – JΛYDΞV
    Dec 14, 2021 at 12:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.