JavaFX Text Font and Position Example

In this JavaFX example, we will show you how to create text and add font to text in the JavaFX application.

We can use javafx.scene.text.Text class to create text-based information on the interface of our JavaFX application. This class provides various methods to alter various properties of the text. We just need to instantiate this class to implement text in our application.

JavaFX Text Font and Position

JavaFX enables us to apply various fonts to the text nodes. We just need to set the property font of the Text class by using the setter method setFont(). This method accepts the object of the Font class.

package com.javafx.examples;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class JavaFXTextFontExample extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Text text = new Text();

        // position of text
        text.setX(100);
        text.setY(100);

        // font for text
        text.setFont(Font.font("Verdana", FontWeight.BOLD, FontPosture.REGULAR, 25));
        text.setText("Welcome to Java Guides");
        Group root = new Group();
        Scene scene = new Scene(root, 500, 400);
        root.getChildren().add(text);
        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX Text Font Example");
        primaryStage.show();
    }

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

The font family is "Verdana", font-weight is bold and font size is 25:

text.setFont(Font.font("Verdana", FontWeight.BOLD, FontPosture.REGULAR, 25));
  • Family: it represents the family of the font. It is of string type and should be an appropriate font family present in the system.
  • Weight: this Font class property is for the weight of the font. There are 9 values that can be used as the font-weight. The values are FontWeight.BLACKBOLDEXTRA_BOLDEXTRA_LIGHTLIGHTMEDIUMNORMALSEMI_BOLDTHIN.
  • Posture: this Font class property represents the posture of the font. It can be either FontPosture.ITALIC or FontPosture.REGULAR.
  • Size: this is a double type property. It is used to set the size of the font.

Output



Comments