How to wrap the text within the width of the window in JavaFX?

JavaObject Oriented ProgrammingProgramming

In JavaFX, the text node is represented by the Javafx.scene.text.Text class. To insert/display text in JavaFx window you need to −

  • Instantiate the Text class.

  • Set the basic properties like position and text string, using the setter methods or, bypassing them as arguments to the constructor.

  • Add the created node to the Group object.

If the length of the lines in the text you have passed, longer than the width of the window part of the text will be chopped as shown below −

As a solution you can wrap the text within the width of the window by setting the value to the property wrapping with, using the setWrappingWidth() method.

This method accepts a double value representing the width (in pixels) of the text. If you pass a value that is less than the width of the window, the text will be wrapped within it(the given width).

Example

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
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 WrappingTheText extends Application {
   public void start(Stage stage) throws FileNotFoundException {
      //Reading the contents of a text file.
      InputStream inputStream = new FileInputStream("D:\\sample.txt");
      Scanner sc = new Scanner(inputStream);
      StringBuffer sb = new StringBuffer();
      while(sc.hasNext()) {
         sb.append(" "+sc.nextLine()+"\n");
      }
      //Creating a text object
      Text text = new Text(10.0, 25.0, sb.toString());
      //Wrapping the text
      text.setWrappingWidth(590);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Wrapping The Text");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

sample.txt

Assume following are the contents of the sample.txt file −

JavaFX is a Java library used to build Rich Internet Applications. The applications written 
using this library can run consistently across multiple platforms. The applications developed 
using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc..
To develop GUI Applications using Java programming language, the programmers rely on libraries 
such as Advanced Windowing Tool kit and Swing. After the advent of JavaFX, these Java programmers 
can now develop GUI applications effectively with rich content.

Output

Font Name: Brush Script MT

Output

raja
Published on 14-Apr-2020 08:39:37
Advertisements