Angel Garcia Angel Garcia - 4 months ago 18
CSS Question

[SOLVED]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:

package dev.angarc.game;

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){
launch(args);
}

@Override
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));
text.setTextAlignment(TextAlignment.CENTER);

// adding to the pane
vbox.getChildren().add(text);

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

}

}

Answer

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">
         <children>
            <Text strokeType="OUTSIDE" strokeWidth="0.0" text="Text" />
         </children>
      </VBox>