Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 362
Victor Grazi Avatar asked Dec 09 '22 06:12

Victor Grazi


2 Answers

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.

like image 189
jewelsea Avatar answered Jan 04 '23 22:01

jewelsea


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);
    }
}
like image 27
James_D Avatar answered Jan 04 '23 22:01

James_D