JavaFX Applying Color and Stroke to Text Example

In this JavaFX example, we will show you how to create text, add font to text and add color 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 Stroke and Color to Text

The following example demonstrates creating text, adding stroke and color to text:

package com.javafx.examples;

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
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 JavaFXFontColorExample extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        // TODO Auto-generated method stub
        Text text = new Text();

        text.setX(100);
        text.setY(100);
        text.setFont(Font.font("Verdana", FontWeight.BOLD, FontPosture.REGULAR, 25));
        text.setFill(Color.BLUE); // setting color of the text to blue
        text.setStroke(Color.BLACK); // setting the stroke for the text
        text.setStrokeWidth(1); // setting stroke width to 2
        text.setText("Welcome to Java Guides");
        Group root = new Group();
        Scene scene = new Scene(root, 500, 200);
        root.getChildren().add(text);
        primaryStage.setScene(scene);
        primaryStage.setTitle("JavaFX Font Color Example");
        primaryStage.show();
    }

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

    }
}

Output



Comments