0

I'm trying to teach myself JavaFX and tried to create a simple smiley face image. But for some reason all my shapes wind up centered instead of at the x&y coordinates that I constructed them with. I can't figure out why. Can anyone help me figure it out?

Here's my code:

import javafx.*;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.Stage;

public class smiley extends Application {

    public static void main(String[] args) {
        launch(args);
    }

    public void start(Stage primaryStage) throws Exception {
        Circle head = new Circle(250, 250, 150);
        head.setFill(Color.YELLOW);
        Circle eyeL = new Circle(200, 175, 25);
        eyeL.setFill(Color.BLACK);
        Circle eyeR = new Circle(300, 175, 25);
        eyeR.setFill(Color.BLACK);
        double[] points = { 250.0, 200.0, 250.0, 275.0, 290.0, 275.0 };
        Polygon nose = new Polygon(points);
        Arc smile = new Arc(275.0, 300.0, 75.0, 50.0, 180.0, 180.0);
        smile.setStroke(Color.RED);
        smile.setFill(Color.YELLOW);

        StackPane smiley = new StackPane();
        smiley.getChildren().add(head);
        smiley.getChildren().add(eyeL);
        smiley.getChildren().add(eyeR);
        smiley.getChildren().add(nose);
        smiley.getChildren().add(smile);

        Scene scene = new Scene(smiley, 500, 500);
        primaryStage.setTitle("Smiley");
        primaryStage.setScene(scene);
        primaryStage.show();

    }

}

And this is what I wind up with

smiley face

Abra
  • 19,142
  • 7
  • 29
  • 41
Gertrude
  • 1
  • 2
  • 7
    A `StackPane` will, by default, center all its children. Since you want to manually position all your shapes you need to use a layout that doesn't manage the position of its children, such as `Pane` or `Group`. Though I suppose the other option is to set the `managed` property of each shape to `false` (but I'd prefer the use-the-appropriate-layout option). – Slaw Aug 02 '20 at 23:14
  • 1
    Try `Pane smiley = new Pane()` or subclasses of `Pane`, seen [here](https://stackoverflow.com/a/37935114/230513). – trashgod Aug 03 '20 at 16:24
  • Possible duplicate. https://stackoverflow.com/questions/55526669/javafx-making-a-face/55527030#55527030 – SedJ601 Aug 04 '20 at 04:16

1 Answers1

0

StackPane lays out its children on top of each other. Just think of a stack of pancakes. The last one goes on top and the first one is at the bottom. If you set a border/padding, then the children will by place in the center within those insets. Additionally, StackPane will resize all the children to fit the content area, but if that's not possible, it will then place it in the center. I don't think that this is your intent here, so try using the Pane class, which StackPane inherits from.

Pane pane = new Pane();
Martin Fall
  • 121
  • 7