7

Can someone please give me an example on how to center text on a JavaFX 2 Canvas?

GraphicsContext has some functions like setTextAlign, but I am not sure on how to use all those methods and which of them I really need. I want to center my text vertically and horizontally.

stefan.at.kotlin
  • 15,347
  • 38
  • 147
  • 270

2 Answers2

23
  1. Set the text align to center.
  2. Set the text baseline to center.
  3. Draw the text in the center of your canvas (by positioning it at half the canvas width and height).

Here is a sample:

import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.geometry.VPos;
import javafx.scene.*;
import javafx.scene.canvas.*;
import javafx.scene.layout.StackPane;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class TextCanvas extends Application {
    @Override public void start(Stage primaryStage) {
        Canvas canvas = new Canvas(175, 40);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        gc.setTextAlign(TextAlignment.CENTER);
        gc.setTextBaseline(VPos.CENTER);
        gc.fillText(
            "Text centered on your Canvas", 
            Math.round(canvas.getWidth()  / 2), 
            Math.round(canvas.getHeight() / 2)
        );

        StackPane layout = new StackPane();
        layout.getChildren().addAll(canvas);

        primaryStage.setScene(new Scene(layout));
        primaryStage.show();
    }
    public static void main(String[] args) { launch(args); }
}

centered text on canvas

jewelsea
  • 150,031
  • 14
  • 366
  • 406
0

you wanna use

  control.setAlignment(Pos.CENTER); and

  control.setStyle("-fx-alignment: CENTER;");

see here for some downloadable sample code of this in action.

Rachel Gallen
  • 27,943
  • 21
  • 72
  • 81
  • 1
    Hmm, unfortunately a Canvas and all its content is one complete node, so I fear this won't work. – stefan.at.kotlin Feb 14 '13 at 19:57
  • I had a rough look at it and my impression is, that this is for positioning nodes in containers, e.g. in a HBox. However a Canvas is not a container / the text in a Canvas is not a Node? – stefan.at.kotlin Feb 14 '13 at 20:17