How to create an Ellipse using JavaFX?

JavaObject Oriented ProgrammingProgramming

A circle is a line forming a closed loop, every point on which is a fixed distance from a center point. A circle is defined by its center and radius: distance from the center to any point on the circle.

In JavaFX an ellipse is represented by the javafx.scene.shape.Ellipse class. This class contains four properties they are −

  • centerX − This property represents the x coordinate of the center of the ellipse, you can set the value to this property using the setCenterX() method.

  • centerY − This property represents y coordinate of the center of the ellipse, you can set the value to this property using the setCenterY() method.

  • radiusX − This property represents the width of the ellipse in pixels, you can set the value to this property using the setRadiusX() method.

  • radiusY − This property represents the height of the ellipse in pixels, you can set the value to this property using the setRadiusY() method.

To create a circle you need to −

  • Instantiate this class.

  • Set the required properties using the setter methods or, bypassing them as arguments to the constructor.

  • Add the created node (shape) to the Group object.

Example

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.shape.Ellipse;
public class DrawingEllipse extends Application {
   public void start(Stage stage) {
      //Drawing a Ellipse
      Ellipse ellipse1 = new Ellipse();
      //Setting the properties of the ellipse
      ellipse1.setCenterX(200.0);
      ellipse1.setCenterY(150.0);
      ellipse1.setRadiusX(100);
      ellipse1.setRadiusY(50);
      //Setting other properties
      ellipse1.setFill(Color.DARKCYAN);
      ellipse1.setStrokeWidth(8.0);
      ellipse1.setStroke(Color.DARKSLATEGREY);
      //Drawing a Ellipse
      Ellipse ellipse2 = new Ellipse();
      //Setting the properties of the ellipse
      ellipse2.setCenterX(450.0);
      ellipse2.setCenterY(150.0);
      ellipse2.setRadiusX(35);
      ellipse2.setRadiusY(100);
      //Setting other properties
      ellipse2.setFill(Color.CHOCOLATE);
      ellipse2.setStrokeWidth(8.0);
      ellipse2.setStroke(Color.BROWN);
      //Setting the Scene
      Group root = new Group(ellipse1, ellipse2);
      Scene scene = new Scene(root, 595, 300, Color.BEIGE);
      stage.setTitle("Drawing an Ellipse");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 14-Apr-2020 07:55:39
Advertisements