我有一个JavaFX Text
,Scene
和Group
Text waitingForKey
Scene scene
Group root
我有一个字符串waitingForKeyString
,我将waitingForKey
添加到 String waitingForKeyString= " Level 2 \n\n" + "Press ENTER to start a new game";
,我希望中心对齐。
问题在于,有时字符串有两个句子,我无法对齐
Scene scene = new Scene(root,SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK);
waitingForKey.setText(waitingForKeyString);
root.getChildren().add(waitingForKey);
OR
String waitingForKeyString ="按ENTER键\ n" + "开始游戏",messageString ="";
THEN
waitingForKeyString
那我怎么能把它与中心对齐呢?当我试图首先对齐{{1}}时,我销毁了第二个`waitingForKeyString和vicecersa。
答案 0 :(得分:4)
您可以使用StackPane
作为Scene
的根,因为它有alignmentProperty
。
如果您想在Nodes
中单独对齐StackPane
,可以使用StackPane
的{{3}}方法。
示例(一个文本在CENTER中对齐,另一个在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);
}
}
答案 1 :(得分:1)
为Text
指定TextAlignment.CENTER
,并使用StackPane
之类的布局,"默认为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);
}
}