![](/img/trans.png)
[英]How do I make an XML layout for a ListView row where there is a TextView left-aligned and a TextView right-aligned?
[英]How to make left-aligned TextFlow in the center of the window in JavaFX
如何使TextFlow中的文本左对齐,但TextFlow位于窗口中央?
我尝试使用 VBox、StackPane 和 BorderPane 来实现它,但它们只能将文本居中对齐,或者使 TextFlow 位于窗口左侧。
但是我实现的效果是这样的:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TextFlow text = new TextFlow(
new Text("Search Everywhere\n"),
new Text("Project View\n"),
new Text("Go to File\n")
);
text.setTextAlignment(TextAlignment.LEFT);
VBox root = new VBox(text);
root.setAlignment(Pos.CENTER);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
}
感谢c0der的提示,我发现FlowPane可以轻松实现这个效果:
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
TextFlow text = new TextFlow(
new Text("Search Everywhere\n"),
new Text("Project View\n"),
new Text("Go to File\n")
);
text.setTextAlignment(TextAlignment.LEFT);
FlowPane root = new FlowPane(text);
root.setAlignment(Pos.CENTER);
primaryStage.setScene(new Scene(root, 400, 400));
primaryStage.show();
}
}
我不确定这正是您要寻找的,但应该让您朝着正确的方向前进。 我添加了颜色,以便您可以看到一个控件在哪里结束,另一个控件在哪里继续。
要完成这项工作,您需要确保 TextFlow 的大小不会超过您想要的大小,否则它不会为您提供预期的行为。 在本例中,我选择 200x200,您将在窗口中央看到它。
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import javafx.stage.Stage;
public class Sample extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
TextFlow tf = new TextFlow();
tf.setStyle("-fx-background-color: red;");
tf.setTextAlignment(TextAlignment.LEFT);
tf.setMaxSize(200, 200);
StackPane sp = new StackPane(tf);
sp.setStyle("-fx-background-color: blue;");
Text t1 = new Text("This is line one, left justified" + System.lineSeparator());
Text t2 = new Text("This is line two, left justified"+ System.lineSeparator());
Text t3 = new Text("This is line three, left justified"+ System.lineSeparator());
Text t4 = new Text("This is line four, left justified"+ System.lineSeparator());
tf.getChildren().addAll(t1, t2, t3, t4);
Scene scene = new Scene(sp);
primaryStage.setScene(scene);
primaryStage.setWidth(600);
primaryStage.setHeight(600);
primaryStage.show();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.