Monday, February 25, 2013

Load True Type Font (ttf) in JavaFX

To load True Type Font (ttf) in JavaFX, create a folder fonts under your Source Packages, copy your ttf file into it. Load the font with Font.loadFont() method.

Save ttf file in /fonts folder.
Save ttf file in /fonts folder.


package javafxttf;

import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;

/**
*
* @web http://java-buddy.blogspot.com/
*/
public class JavaFXTTF extends Application {

@Override
public void start(Stage primaryStage) {

Font myFontloadFontAirstreamNF20 =
Font.loadFont(getClass()
.getResourceAsStream("/fonts/AirstreamNF.ttf"), 20);

Button btn = new Button();
btn.setFont(myFontloadFontAirstreamNF20);
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Hello World!");
}
});

StackPane root = new StackPane();
root.getChildren().add(btn);

Scene scene = new Scene(root, 300, 250);

primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}

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


Load True Type Font (ttf) in JavaFX
Load True Type Font (ttf) in JavaFX


Related article: Apply system installed fonts.

1 comment: