Victor Grazi
Victor Grazi

Reputation: 16480

How can I rotate a label

In JavaFX 8 I would like to specify the css to rotate a Label so that instead of the text going from left to right, it goes from bottom to top.

How can I do that?

Upvotes: 4

Views: 7437

Answers (3)

NebuCodeNezzar
NebuCodeNezzar

Reputation: 355

You can easily set a label's rotation by specifying the degrees of rotation as per the code below:

label.setRotate(45)

for 45 degrees, for example.

if you want to set it after some operations, that is, after the label has been displayed in the User Interface, you can use

Platform.runLater() lambda expression. i.e

Platform.runLater(()->
   label.setRotate(45);
  )

Upvotes: 1

jewelsea
jewelsea

Reputation: 159291

Any node can have it's rotation styled via CSS using the -fx-rotate css attribute.

This is the angle of the rotation in degrees. Zero degrees is at 3 o'clock (directly to the right). Angle values are positive clockwise. Rotation is about the center.

So in your code or FXML you can have:

label.setStyle("vertical");

And in your css stylesheet you can define:

.vertical { -fx-rotate: -90; }

Also note James_D's answer suggestion of wrapping the label in a Group to account for the rotation when performing layout bounds calculations.

Upvotes: 8

James_D
James_D

Reputation: 209330

Call setRotate on the label to rotate it about its center.

To allow layout panes to properly measure the bounds of the label after rotation, wrap it in a Group:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class RotatedLabelTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        Label label1 = new Label("Hello");
        Label label2 = new Label("World");

        label1.setRotate(-90);
        Group labelHolder = new Group(label1);

        HBox root = new HBox(5, labelHolder, label2);
        root.setAlignment(Pos.CENTER);

        Scene scene = new Scene(root, 250, 150);
        primaryStage.setScene(scene);
        primaryStage.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

Upvotes: 7

Related Questions