# How to wrap the text of a label in JavaFX?

JavaFXObject Oriented ProgrammingProgramming

You can display a text element/image on the User Interface using the Label component. It is a not editable text control, mostly used to specify the purpose of other nodes in the application.

In JavaFX, you can create a label by instantiating the javafx.scene.control.Label class. To create a label, you need to instantiate this class.

Once you have created a label, you can set the maximum width and height of it using the setMaxWidth() and setMaxHeight() methods respectively.

Once you set the maximum with of a label the contents of it exceeding the specified the width will be chopped off.

To avoid this you can wrap the text within the specified width you need to invoke the setWrapText() method. On passing true as an argument to this method the contents of the label exceeding the specified width will be wrapped into the next line.

## Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
public class LabelWrapExample extends Application {
public void start(Stage stage) {
String text = "Tutorials Point originated from the idea that there exists a class
of readers who respond better to online content and prefer to learn new skills at
their own pace from the comforts of their drawing rooms.";
//Creating a Label
Label label = new Label(text);
//wrapping the label
label.setWrapText(true);
//Setting the alignment to the label
label.setTextAlignment(TextAlignment.JUSTIFY);
//Setting the maximum width of the label
label.setMaxWidth(200);
//Setting the position of the label
label.setTranslateX(25);
label.setTranslateY(25);
Group root = new Group();
//Setting the stage
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Label Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

## Output

Published on 18-May-2020 09:35:24