Home > Java > javaTutorial > body text

How to draw geometric 2D shapes in JavaFX?

PHPz
Release: 2023-09-04 16:01:06
forward
845 people have browsed it

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.

Creating 2D Shapes

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();
Copy after login
  • 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);
Copy after login
  • 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);
Copy after login

Example

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);
   }
}
Copy after login

Output

How to draw geometric 2D shapes in JavaFX?

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template