【问题标题】:Setting the alignment of a node without using BorderPane?在不使用 BorderPane 的情况下设置节点的对齐方式?
【发布时间】:2019-08-04 14:12:01
【问题描述】:

所以我有一个文本节点,我想将它定位在场景的右上角。大多数方法都声明使用BorderPane,但在我的情况下,我场景中的一些其他节点正在使用Pane,这也是我的根窗格,因此显而易见的解决方法是将您想要的节点添加到BorderPane 和将BorderPane 添加到根Pane

但是BorderPane 似乎与Pane 不兼容。也就是说,BorderPane 的所有节点都不会显示。 BorderPane 也不支持基于它们的平移 X 和 Y 定位节点。(即 setLayoutX() 不起作用。)因此,我什至无法将我的根 Pane 设置为 BorderPane

这是我尝试过的:

public class foo {
    private Pane root = new Pane();
    private BorderPane borderPane = new BorderPane();
    private Scene scene = new Scene(root, 1366, 768);

    public foo(){
        Text text1 = new Text("test1");
        text1.setLayoutX(11); // Ignore this if you want.
        test1.setLayoutY(11);

        Text text2 = new Text("test2");

        root.getChildren().add(test1);
        borderPane.setRight(text2);
        root.getChildren().add(borderPane);

        // Display the scene on a stage.
    }
}

这里只显示test1,看不到test2。 有没有办法我可以使用BorderPaneBorderPane将此文本放置在屏幕的右上方?

【问题讨论】:

    标签: java javafx


    【解决方案1】:

    Pane 只是将孩子调整为首选大小。由于您只将 Text 节点作为 BorderPane 的子节点,因此其首选大小是子节点的大小。

    在这种情况下,我建议使用不同的布局,例如

    堆栈窗格

    这允许您使用StackPane.setAlignment(child, newAlignment); 在布局中设置节点的对齐方式。缺点是设置绝对位置需要您使子节点不受管理(有一些副作用)或指定 4 个值(Insets 实例)作为边距。

    Text text1 = new Text("test1");
    StackPane.setMargin(text1, new Insets(11, 0, 0, 11));
    StackPane.setAlignment(text1, Pos.TOP_LEFT);
    
    Text text2 = new Text("test2");
    StackPane.setAlignment(text2, Pos.TOP_RIGHT);
    
    root = new StackPane(text1, text2);
    

    AnchorPane

    这不允许居中对齐,但它允许您使用layoutXlayoutY 设置绝对位置,就像在Pane 中所做的那样。您可以设置锚属性来指定子元素与顶部、左侧、右侧和/或底部的距离:

    Text text1 = new Text("test1");
    text1.setLayoutX(11);
    text1.setLayoutY(11);
    
    Text text2 = new Text("test2");
    AnchorPane.setRightAnchor(text2, 0d);
    AnchorPane.setTopAnchor(text2, 0d);
    
    root = new AnchorPane(text1, text2);
    

    【讨论】:

    • 我似乎无法让它工作。您可以在代码 sn-p 中包含您使用的根目录等吗?我也可以将 StackPane 添加到我的窗格中吗? StackPane 包含我想要对齐的文本,Pane 包含所有其他内容。这样我就可以将 StackPane 添加到我的根窗格中。谢谢。
    • 您不能使用Pane 作为您想要右对齐的节点的祖先(除非您希望布局不响应或使用绑定)。假设text1 是您要绝对定位的节点,而text2 是要向左对齐的节点,则代码sn-ps 中分配给root 变量的值应该替换代码中的根;它们应该用作场景的根。您仍然可以添加 Pane 作为子项,而不是添加例如text1直接...
    猜你喜欢
    • 2016-04-28
    • 2023-03-19
    • 2015-11-11
    • 1970-01-01
    • 2016-01-19
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多