How to make a text bold and italic in JavaFX?


You can set the desired font to the text node in JavaFX using the setFont() method. This method accepts an object of the class javafx.scene.text.Font.

The Font class represents the fonts in JavaFX, this class provides several variants of a method named font() as shown below −

font(double size)
font(String family)
font(String family, double size)
font(String family, FontPosture posture, double size)
font(String family, FontWeight weight, double size)
font(String family, FontWeight weight, FontPosture posture, double size)

Where,

  • size (double) represents the size of the font.

  • family (string) represents the family of the font that we want to apply to the text. You can get the names of installed font families using the getFamilies() method.

  • weight represents the weight of the font (one of the constants of the FontWeight Enum − BLACK, BOLD, EXTRA_BOLD, EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN).

  • posture represents the font posture (one of the constants of the FontPosture Enum: REGULAR, ITALIC).

To make a text bold create a font bypassing FontWeight.BOLD or, FontWeight.EXTRA_BOLD as the value of the parameter weight and, to make a text italic pass FontPosture.ITALIC as the value of the parameter posture.

Example

import java.io.FileNotFoundException;
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
public class Bold_Italic extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Creating a text object
      String str = "Welcome to Tutorialspoint";
      Text text = new Text(30.0, 80.0, str);
      //Setting the font bold and italic
      Font font = Font.font("Verdana", FontWeight.BOLD, FontPosture.ITALIC, 35);
      text.setFont(font);
      //Setting the color of the text
      text.setFill(Color.DARKCYAN);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 150, Color.BEIGE);
      stage.setTitle("Bold And Italic");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

Updated on: 16-May-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements