JavaFX – 以场景为中心的文本
我有一个JavaFX Text
, Scene
和Group
Text waitingForKey Scene scene Group root
我有一个字符串String waitingForKeyString
,我正在添加到waitingForKey
,我想要一个中心对齐。
问题是,有时字符串有两个句子,我无法对齐它
String waitingForKeyString= " Level 2 \n\n" + "Press ENTER to start a new game";
要么
String waitingForKeyString =“按ENTER \ n”+“开始游戏”,messageString =“”;
然后
Scene scene = new Scene(root,SCREEN_WIDTH, SCREEN_HEIGHT, Color.BLACK); waitingForKey.setText(waitingForKeyString); root.getChildren().add(waitingForKey);
那我怎么能把它与中心对齐呢? 当我尝试对齐第一个waitingForKeyString
我销毁了第二个`waitingForKeyString和vicecersa。
您可以使用StackPane
作为Scene
根,因为它具有alignmentProperty
。
如果要在StackPane
单独对齐Nodes
,可以使用StackPane
public static void setAlignment(Node child, Pos value)
方法。
示例(一个文本在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); } }
为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); } }