JavaFX - 以场景为中心的文本 [英] JavaFX - centered Text in Scene

查看:206
本文介绍了JavaFX - 以场景为中心的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaFX 文本场景

I've got a JavaFX Text,Scene and Group

Text waitingForKey
Scene scene
Group root

我有一个字符串String waitingForKeyString 我要添加到 waitingForKey 我希望有一个居中对齐。

I have a string String waitingForKeyString which I'm adding to waitingForKeyand I want to have a center align.

问题是有时字符串有两个句子,我无法对齐它

The problem is that sometimes the string has two sentences and I can't aligned it

 String waitingForKeyString= " Level 2 \n\n" + "Press ENTER to start a new game";

OR

String waitingForKeyString =Press输入\ n+
开始游戏,messageString =;

String waitingForKeyString= " Press ENTER \n"+ "to start the game", messageString="";

那么

Scene scene = new Scene(root,SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK);
waitingForKey.setText(waitingForKeyString);
root.getChildren().add(waitingForKey);

那么我怎样才能将它与中心对齐?当我尝试对齐第一个 waitingForKeyString 时,我销毁了第二个`waitingForKeyString和vicecersa。

So how could I align this to center? When I tried to align first waitingForKeyStringI destroyed the second `waitingForKeyString and vicecersa.

推荐答案

您可以使用 StackPane 作为场景的根目录,因为它有 alignmentProperty

You could use a StackPane as root of your Scene as it has an alignmentProperty.

如果你想在 StackPane 中单独对齐节点你可以使用 public static void setAlignment(Node child,Pos value) StackPane方法

If you want individually align Nodes in the StackPane you can use public static void setAlignment(Node child, Pos value) method of StackPane.

示例(一个文本在CENTER中对齐,另外一个呃其中一个在左上角对齐)

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);
    }
}

这篇关于JavaFX - 以场景为中心的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆