JavaFX: Setting the text for display

This entry is part 6 of 55 in the series JavaFX

Using our previous example on displaying a text string, we will go through the process on how we have created a Text object, setting the text color and the font of the text.

The 4 lines of statement that we used are shown here:

Text txt = new Text();
txt.setFill(Color.BLUE);
txt.setFont(Font.font("Times New Roman", 36));
txt.setText("Hello World");

In the first line above, we create a Text object with the object name txt.

As txt is now a Text object, we could make use of the methods that are associated with the Text object.

The methods that we used here are setFill, setFont and setText.  All these are member functions of Text object.

Notice that in our import statements, we have 2 classes related to Font and Color.

Font and Color are known as static classes.  We do not have to declare an instance of the Color class to access its property, which is BLUE in this case.  We set the color property by using Color.Blue where Color is actually the name of the class.

The same goes to setting the font type where we access the font type by using Font.font(). Font is similar to the name of the class as shown in the import statement.

package javafxapplication4;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.stage.Stage;

public class JavaFXApplication4 extends Application {

    @Override
    public void start(Stage primaryStage) {

        primaryStage.setTitle("JavaFX Program!");

        StackPane stackpane = new StackPane();

        Scene scene = new Scene(stackpane, 300, 250);
        primaryStage.setScene(scene);

        Text txt = new Text();
        txt.setFill(Color.BLUE);
        txt.setFont(Font.font("Times New Roman", 36));
        txt.setText("Hello World");

        stackpane.getChildren().add(txt);

        primaryStage.show();
    }

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

}

h1

 

Series Navigation<< JavaFX: Common classes
JavaFX: Stackpane and z-order >>