JavaFX - 以场景为中心的文本 [英] JavaFX - centered Text in Scene
问题描述
我有一个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 waitingForKey
and 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 waitingForKeyString
I 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屋!