Generally speaking, 2D shapes are geometric figures that can be drawn on the XY plane, including lines, rectangles, circles, etc.
javafx.scene.shapeThe package provides various classes, each class represents/defines a 2D geometric object or an operation on them. The class named Shape is the base class for all 2D shapes in JavaFX.
To draw 2D geometric shapes using JavaFX, you need:
Instancing Class - Instantiation corresponding class. For example, if you want to draw a circle, you need to instantiate the Circle class as follows:
//Drawing a Circle Circle circle = new Circle();
Set the properties - Use its corresponding Class methods set the shape's properties. For example, to draw a circle, you need a center and a radius, which you can set using the setCenterX(), setCenterY(), and setRadius() methods respectively.
//Setting the properties of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); circle.setRadius(100.0f);
Add the shape object to the group − Finally, pass the created shape as a parameter to the group’s constructor as follows Display:
Group root = new Group(circle);
import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Circle; public class CircleExample extends Application { public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the properties of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); circle.setRadius(100.0f); //Creating a Group object Group root = new Group(circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle("Drawing a Circle"); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } }
The above is the detailed content of How to draw geometric 2D shapes in JavaFX?. For more information, please follow other related articles on the PHP Chinese website!