SamyLouail SamyLouail - 4 months ago 40
Java Question

How do I create a triangle using JavaFX?

How can I create a triangle using JavaFX?
I have already tried these but I don't know how to fix it exactly :

Polygon triangle = new Polygon();
triangle.getPoints().setAll(
50, 50,
60, 60,
20, 40
);

Answer

Replace triangle.getPoints().setAll.. with triangle.getPoints().addAll(

Explanation:

yor are adding 3 points, the x0=50,y0=50 then the x0=60,y0=60 and then x0=20,y0=40, those are the vertex of the triangle...

this represents a triangle like this (Be careful of not plotting a line or a weird figure)

enter image description here

The following snippet will generate a polygon like the image below.

public class Main extends Application {
      @Override
      public void start(Stage stage) {
        Group root = new Group();
        Scene scene = new Scene(root, 260, 80);
        stage.setScene(scene);

        Group g = new Group();

        Polygon polygon = new Polygon();
        polygon.getPoints().addAll(new Double[]{
            0.0, 0.0,
            20.0, 10.0,
            10.0, 20.0 });

        g.getChildren().add(polygon);

        scene.setRoot(g);
        stage.show();
      }

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

enter image description here