0

I want to make a rectangle with the polygon class. I know you can use the rectangle class, but it needs to be made under the polygon class. How can i set paramters to initalize a rectangle. Im using javafx.

        Polygon polygon = new Polygon();
        
        //Adding coordinates to the polygon 
         polygon.getPoints().addAll(new Double[]{ 
         200.0, 50.0, 
         400.0, 50.0, 
         450.0, 250.0,          
         400.0, 250.0, 
         100.0, 250.0,                   
         100.0, 150.0,       
        }); 

i started with this just as a template, but it makes a pentagon.

galapagos
  • 35
  • 5
  • 1
    The parameter is just an array of double values representing the points in the polygon, in `{x1, y1, x2, y2, …, xn, yn}` order. Just pass in the coordinates of the vertices of your rectangle. – James_D Jul 21 '22 at 17:10
  • What resource is that information from – galapagos Jul 21 '22 at 17:56
  • 1
    From the [documentation](https://openjfx.io/javadoc/18/javafx.graphics/javafx/scene/shape/Polygon.html): "_Creates a polygon, defined by an array of x,y coordinates._" Though I will agree that said documentation should be clearer. – Slaw Jul 21 '22 at 17:59
  • 1
    It’s not completely explicit, but the only reasonable interpretation of “defined by an array of x, y coordinates” in the [documentation](https://openjfx.io/javadoc/17/javafx.graphics/javafx/scene/shape/Polygon.html) – James_D Jul 21 '22 at 18:00

1 Answers1

4

Making a rectangle with Polygon instance

From Doc :

a polygon, defined by an array of x,y coordinates. The Polygon class is similar to the Polyline class, except that the Polyline class is not automatically closed.

So , a Polygon is made of 2d xy coordinates where the last 2dpoint make an edge with the first one automatyically closing its shape

In this example a 200*50 pixels rectangle is made like so

rectangle xy

App.java

public class App extends Application {

    @Override
    public void start(Stage stage) {
        Polygon polygon = new Polygon();
        polygon.getPoints().addAll(new Double[]{
            0.0, 0.0,// a
            200.0, 0.0,//b
            200.0, 50.0,//d
            0.0, 50.0 //c   
        });
        polygon.setFill(Color.YELLOWGREEN);
        polygon.setStroke(Color.BLACK);
      
        
        var scene = new Scene(new StackPane(polygon), 640, 480);
        stage.setScene(scene);
        stage.show();
    }

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

}

result :

enter image description here

Giovanni Contreras
  • 2,345
  • 1
  • 13
  • 22