user11631934
user11631934

Reputation:

Setting the alignment of a node without using BorderPane?

So I have a Text node which I want to position at the Top-Right side of the scene. Most methods state to use BorderPane, but in my case some of the other nodes in my scene are using Panewhich is also my root pane, so the obvious workaround is to add the nodes you want to the BorderPane and add the BorderPane to the root Pane.

However BorderPane does not seem to be compatible with the Pane. That is, all the nodes of the BorderPane won't be shown. Also positioning the nodes based on their translate X and Y are not supported in BorderPane as well.(i.e. setLayoutX() does not work.) Because of this I cannot even make my root Pane to BorderPane.

Here is what I've tried:

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.
    }
}

Here only test1 is shown and test2 is not seen. Is there a way I can position this text on the RIGHT TOP side of the screen without using BorderPane?

Upvotes: 0

Views: 217

Answers (1)

fabian
fabian

Reputation: 82461

Pane just resizes the children to the preferred size. Since you only place the Text node as child of the BorderPane, its preferred size is the size of the child.

In this case I recommend using a different layout, e.g.

StackPane

This allows you set the alignment of a node within the layout using StackPane.setAlignment(child, newAlignment);. The drawback is that setting an absolute position requires you to either make the child unmanaged (with some side effects) or specifying 4 values (an Insets instance) as margin.

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

This does not allow for center alignments, but it allows you to set absolute positions using layoutX and layoutY just the way you'd do in a Pane. You can set anchor properties to specify the distance of a child from the top, left, right and/or bottom:

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);

Upvotes: 2

Related Questions