I\'ve got a JavaFX Text
,Scene
and Group
Text waitingForKey
Scene scene
Group root
I have a string St
Specify TextAlignment.CENTER
for the Text and use a layout like StackPane that "defaults to Pos.CENTER
."
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
/**
* @see http://stackoverflow.com/a/37541777/230513
*/
public class Test extends Application {
@Override
public void start(Stage primaryStage) {
Text waitingForKey = new Text("Level 2 \n\n" + "Press ENTER to start a new game");
waitingForKey.setTextAlignment(TextAlignment.CENTER);
waitingForKey.setFont(new Font(18));
waitingForKey.setFill(Color.ALICEBLUE);
StackPane root = new StackPane();
root.getChildren().add(waitingForKey);
Scene scene = new Scene(root, 320, 240, Color.BLACK);
primaryStage.setTitle("Test");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
You could use a StackPane as root of your Scene
as it has an alignmentProperty.
If you want individually align Nodes
in the StackPane
you can use public static void setAlignment(Node child, Pos value) method of StackPane
.
Example (one Text is aligned in CENTER, another one is aligned in TOP LEFT)
public class Main extends Application {
@Override
public void start(Stage primaryStage) {
try {
StackPane root = new StackPane();
Text text2 = new Text("I will be aligned TOPLEFT");
Text text = new Text(" Level 2 \n\n" + "Press ENTER to start a new game");
text.setTextAlignment(TextAlignment.CENTER);
root.getChildren().addAll(text2, text);
StackPane.setAlignment(text2, Pos.TOP_LEFT);
StackPane.setAlignment(text, Pos.CENTER);
Scene scene = new Scene(root, 400, 400);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}