📜  JavaFX 2D Shapes(1)

📅  最后修改于: 2023-12-03 15:31:35.612000             🧑  作者: Mango

JavaFX 2D Shapes

JavaFX provides a set of predefined 2D shapes that can be used to create complex graphical interfaces. These shapes are defined by their geometry, which can be modified by changing their properties such as fill, stroke, stroke width, etc.

In this article, we will explore the different 2D shapes that JavaFX provides and how to use them in our applications.

Rectangle

The Rectangle class represents a rectangular shape with the given width and height. We can use the following code snippet to create a rectangle object in JavaFX.

Rectangle rectangle = new Rectangle(x, y, width, height);
rectangle.setFill(Color.BLUE);
pane.getChildren().add(rectangle);
Circle

The Circle class represents a circular shape with the given radius. We can use the following code snippet to create a circle object in JavaFX.

Circle circle = new Circle(centerX, centerY, radius);
circle.setFill(Color.RED);
pane.getChildren().add(circle);
Ellipse

The Ellipse class represents an elliptical shape with the given horizontal radius and vertical radius. We can use the following code snippet to create an ellipse object in JavaFX.

Ellipse ellipse = new Ellipse(centerX, centerY, radiusX, radiusY);
ellipse.setFill(Color.GREEN);
pane.getChildren().add(ellipse);
Line

The Line class represents a straight line segment between two points. We can use the following code snippet to create a line object in JavaFX.

Line line = new Line(startX, startY, endX, endY);
line.setStrokeWidth(3.0);
line.setStroke(Color.ORANGE);
pane.getChildren().add(line);
Polyline

The Polyline class represents a series of connected line segments. We can use the following code snippet to create a polyline object in JavaFX.

Polyline polyline = new Polyline();
polyline.getPoints().addAll(new Double[]{
    x1, y1, x2, y2, x3, y3, ... });
polyline.setStrokeWidth(2.0);
polyline.setStroke(Color.PURPLE);
pane.getChildren().add(polyline);
Polygon

The Polygon class represents a closed polygonal shape defined by its vertices. We can use the following code snippet to create a polygon object in JavaFX.

Polygon polygon = new Polygon();
polygon.getPoints().addAll(new Double[]{
    x1, y1, x2, y2, x3, y3, ... });
polygon.setFill(Color.YELLOW);
pane.getChildren().add(polygon);
Conclusion

JavaFX provides a rich set of 2D shapes that can be used to create graphical interfaces in our applications. The above examples show how these shapes can be created and customized using different properties such as fill, stroke, stroke width, etc.