Angel Garcia Angel Garcia - 1 year ago 109
CSS Question

Having trouble aligning text using javaFX

I barely started learning javaFX today, and I'm really confused about the text node. The text I made won't align in the center. I tried using a Pane, GridPane, and now a VBox. Does that have anything to do with it?

-fx-text-alignment: center;
But that didn't work either. Im really new to this. Thank you anyone for the help! Here is my code:


import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;

public class Game extends Application{

public static void main(String[] args){

public void start(Stage stage){

VBox vbox = new VBox();

// Component stuff

Text text = new Text("This Text Wont Align To The Center!");
text.setFont(Font.font("Arial", FontWeight.NORMAL, FontPosture.REGULAR, 20));

// adding to the pane

// Stuff to set up the window.
stage.setScene(new Scene((vbox), 640, 430));
stage.setTitle("Text Game");



Answer Source

You want to tell your CONTAINER what alignment to use.

You can manage the alignment of nodes and panes by using the setAlignment() method for the panes. Alignment constants are available in the enum types in the javafx.geometry package.

HBox hbox= new HBox();
hbox.setAlignment(Pos.CENTER);//The overall alignment of children within the hbox's width and height.

In case you will want to use FXML

<VBox alignment="CENTER" prefHeight="200.0" prefWidth="100.0" BorderPane.alignment="CENTER">
            <Text strokeType="OUTSIDE" strokeWidth="0.0" text="Text" />