Thursday 10 May 2018

JavaFX: Label: Align label text

By using 'setTextAlignment' method, you can change the position of the label content within its layout area.

Signature of 'setTextAlignment' method
public final void setTextAlignment(TextAlignment value)

TestAlignment is an enum type with below values.

Alignment value
Description
LEFT
Represents text alignment to the left
CENTER
Represents centered text alignment
RIGHT
Represents text alignment to the right
JUSTIFY
Represents justified text alignment.

Ex
Label label1 = new Label("Hello World");
label1.setTextAlignment(TextAlignment.JUSTIFY);
label1.setWrapText(true);

LabelApp.java
package com.sample.demos;

import static javafx.geometry.Pos.CENTER;

import java.io.FileNotFoundException;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class LabelApp extends Application {

 @Override
 public void start(Stage primaryStage) throws FileNotFoundException {
  Label label1 = new Label("Hello World");
  label1.setTextAlignment(TextAlignment.JUSTIFY);
  label1.setWrapText(true);
 
  VBox vBox = new VBox(10, label1);
  vBox.setAlignment(CENTER);

  Scene scene = new Scene(vBox, 200, 200);

  /* Set the scene to primaryStage, and call the show method */
  primaryStage.setTitle("JavaFX Label Example");
  primaryStage.setScene(scene);
  primaryStage.show();
 }

}

TestFX.java
package com.sample.demos;

import javafx.application.Application;

public class TestFX {
 public static void main(String args[]) {
  Application.launch(LabelApp.class, args);
 }
}




Previous                                                 Next                                                 Home

1 comment:

  1. The right align doesn't work.

    @Override
    public void start(Stage primaryStage) throws FileNotFoundException {
    Label label1 = new Label("Hello World");
    label1.setTextAlignment(TextAlignment.RIGHT);
    label1.setWrapText(true);
    label1.setBorder(new Border(new BorderStroke(Color.RED, Color.RED, Color.RED, Color.RED,
    BorderStrokeStyle.SOLID, BorderStrokeStyle.SOLID, BorderStrokeStyle.SOLID, BorderStrokeStyle.SOLID, new CornerRadii(0 * 0.0125), BorderWidths.DEFAULT, new Insets(1))));

    label1.setMaxWidth(200);

    VBox vBox = new VBox(10, label1);
    vBox.setAlignment(CENTER);

    Scene scene = new Scene(vBox, 200, 200);

    /* Set the scene to primaryStage, and call the show method */
    primaryStage.setTitle("JavaFX Label Example");
    primaryStage.setScene(scene);
    primaryStage.show();
    }

    ReplyDelete