Mastering JavaFX 10
上QQ阅读APP看书,第一时间看更新

Closed shapes

There are just four options here—Rectangle, Circle, Ellipse, and Polygon. They mostly don't have any special API, just a minimum required by basic math to describe their form.

The only small difference is Rectangle, which can have rounded corners, controlled by the setArcHeight() and setArcWidth() methods. 

For the polygon, you need to provide the coordinates of each vertex through the getPoints() method. 

For example, take a look at the following code:

 // chapter2/shapes/ClosedShapes.java
Rectangle rect = new Rectangle(50,50);
rect.setArcHeight(10);
rect.setArcWidth(10);
rect.setFill(Color.DARKGREY);

Circle circle = new Circle(50);
circle.setFill(Color.DARKGREY);

Ellipse ellipse = new Ellipse();
ellipse.setRadiusX(60);
ellipse.setRadiusY(40);
ellipse.setFill(Color.DARKGREY);

Polygon polygon = new Polygon();
polygon.setFill(Color.DARKGREY);
polygon.getPoints().addAll(
0.0, 0.0,
50.0, 30.0,
10.0, 60.0);

// adding 4 shapes to the scene
HBox hbox = new HBox(20);
hbox.setPadding(new Insets(20));
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().addAll(rect, circle, ellipse, polygon);
primaryStage.setScene(new Scene(hbox, 500, 150));

You can match all four shapes on this screenshot:

Note that you can have crossing edges for the polygon. JavaFX will do its best to determine which parts of such polygons are internal, judging by the starting point:

polygon.getPoints().addAll(
0., 0.,
50., 0.,
0., 50.,
50., 50.,
30., -10.,
20.,70.);

The preceding code draws the following shape: