How to draw custom shapes in JavaFX using the Path class?

JavaObject Oriented ProgrammingProgramming

The javafx.scene.shape package provides classes using which you can draw various 2D shapes, but these are just primitive shapes like line, circle, polygon, and ellipse, etc…

Therefore, if you want to draw complex custom shapes you need to use the Path class.

The Path Class

The Path class represents the geometrical outline of a shape and is attached to an observable list which holds various Path Elements such as MoveTo, LineTo, HlineTo, VlineTo, ArcTo, QuadCurveTo, CubicCurveTo.

The constructor of this class accepts variable arguments of the type PathElement and constructs a path based on the given path elements.

Example

The Path Element MoveTo is used to move the current position of the path to a specified point and the LineTo draws a line from current coordinates to the specified ones.

In the following example, we are trying to draw a custom complex shape using the MoveTo PathTo and Path classes −

import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.LineTo;
import javafx.scene.shape.MoveTo;
import javafx.scene.shape.Path;
public class ComplexShape extends Application {
   public void start(Stage stage) {
      //Drawing the shape
      MoveTo moveTo = new MoveTo(108, 71);
      LineTo line1 = new LineTo(321, 161);
      LineTo line2 = new LineTo(126,232);
      LineTo line3 = new LineTo(232,52);
      LineTo line4 = new LineTo(269, 250);
      LineTo line5 = new LineTo(108, 71);  
      //Creating a Path
      Path path = new Path(moveTo, line1, line2, line3, line4, line5);
      //Preparing the Stage object
      Group root = new Group(path);
      Scene scene = new Scene(root, 600, 300);
      stage.setTitle("Drawing an arc through a path");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

Output

raja
Published on 14-Apr-2020 07:03:37
Advertisements