user7069368
user7069368

Reputation:

setX and setY not working when trying to position images

I am having problems with positioning my images in my JavaFX program using setX and setY on the ImageView's for the images. I am not sure what is the problem? Appreciate any help given!
Here's my code:

        Image rocket2 = new Image("img/Rocket.png");
        ImageView iv1 = new ImageView(rocket2);
        iv1.setX(60);
        iv1.setY(44);

        Image rocket1 = new Image("img/Rocket.png");
        ImageView iv2 = new ImageView(rocket1);
        iv2.setX(5);
        iv2.setY(16);

        Image background = new Image("img/space.png");
        ImageView iv3 = new ImageView(background);

        StackPane root = new StackPane();
        root.getChildren().addAll(iv3, iv2, iv1);
        Scene scene = new Scene(root, 300, 300);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.setTitle("Space stuff");
        primaryStage.show();

I suspect that something goes wrong because I have set a background image.
img here on what's happening

Upvotes: 5

Views: 11035

Answers (3)

404KnowledgeNotFound
404KnowledgeNotFound

Reputation: 181

If you however want for whatever reason to position a item in a StackPane you can use setTranslateX and setTranslateY. Theese methods set the x and y values AFTER the StackPane has done its layouting, so you will have a different starting position depending on the Alignment your StackPane uses for its children.

Upvotes: 2

jewelsea
jewelsea

Reputation: 159291

Don't place your items in a StackPane if you want to explicitly define their layout positions (setX and setY). A StackPane is a managed layout pane. It will automatically set the location of items added to it (default is to center everything one on top of the other inside the StackPane).

Instead use a Pane or a Group, which are not managed layout panes and allow you to layout your content in the Pane however you wish.

To layout your content inside the Pane, you can use setLayoutX and setLayoutY rather than setX and setY, though I guess setX and setY should also work (I've never used them before on ImageView).

Pavlo, already created an answer while I was typing this (so this answer is a duplicate), but I'll leave this as it adds a bit more explanation.

Upvotes: 4

Pavlo Viazovskyy
Pavlo Viazovskyy

Reputation: 937

Replacing StackPane with Pane should solve the problem.

Upvotes: 3

Related Questions