Search code examples
jsonjavafxpane

JavaFX How to center JSON map in a Pane


I'm trying to display several individual maps of the user's choice drawn from JSON coordinates on a pane. Right now, the map's being drawn in the top left corner. I need that map to be drawn into the center of the pane, not in a corner, so it can be scaled properly/universally. If I use a StackPane and setAlignment(Pos.CENTER); then all the separate regions (they are drawn individually) that make up the map are being drawn in the pane not the map as a whole.

Here's the code for drawing the regions on the pane:

public void addPolygon(List<Point2D>coordinates, Color color){
    Polygon polygon = new Polygon();
    for(Point2D point : coordinates)
        polygon.getPoints().addAll(point.getX(), point.getY());

        //outline each polygon in black
        polygon.setStroke(Color.BLACK);
        polygon.setStrokeWidth(0.08);

        //sets the color of the polygon derived from a random color generator
        polygon.setFill(color);

    //add created polygons to pane
    mapPane.getChildren().add(polygon);

How can I tweak it to appear in the center? Thanks!


Solution

  • I think the solution would be to put the individual regions into a Group. Then put the Group into the centered StackPane.

    private Group mapGroup = new Group();
    
    public void addPolygon(List<Point2D>coordinates, Color color){
        Polygon polygon = new Polygon();
        for(Point2D point : coordinates)
            polygon.getPoints().addAll(point.getX(), point.getY());
    
            //outline each polygon in black
            polygon.setStroke(Color.BLACK);
            polygon.setStrokeWidth(0.08);
    
            //sets the color of the polygon derived from a random color generator
            polygon.setFill(color);
    
        //add created polygons to pane
        mapGroup.getChildren().add(polygon);