How to create text node in JavaFX?

JavaObject Oriented ProgrammingProgramming

In JavaFX, the text node is represented by the javafx.scene.text.Text class. You can add text to a JavaFX window by instantiating this class.

Following are the basic properties of the text node −

  • X − This property represents x coordinate of the text. You can set value to this property using the setX() method.

  • Y − This property represents y coordinate of the text. You can set value to this property using the setY() method.

  • text − This property represents the text that is to be displayed on the JavaFX window. You can set value to this property using the setText() method.

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, by passing them as arguments to the constructor.

  • Add the created node to the Group object.

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.Text;
public class CreatingText 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");
      }
      String str = sb.toString();
      //Creating a text object
      Text text = new Text();
      //Setting the properties of text
      text.setText(str);
      text.setWrappingWidth(580);
      text.setX(10.0);
      text.setY(25.0);
      //Setting the stage
      Group root = new Group(text);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Displaying 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

raja
Published on 14-Apr-2020 11:41:49
Advertisements