Author: saqibkhan

  • Stroke Property

    The Stroke Fill property is used to change the colours of 2D object itself. However, we can also change the colour of a 2D object’s boundary.

    In JavaFX, while creating a 2D object, there are only two parts you can work with, if you want to improve the quality of the shape; i.e., the enclosed area of the shape and the boundary of the shape. Hence, the properties provided by JavaFX include designing both these parts.

    In this chapter, we will learn about the Stroke property in detail.

    Stroke Property

    The Stroke property in JavaFX is used to change colours of the shape boundary. This property is of the type Paint and it represents the color of the boundary line of the shape. You can set a value to this property using the method setStroke(). This method is a part of javafx.scene.paint package and takes the Color object as a parameter value as shown below −

    path.setStroke(Color.RED)

    By default, the color of the stroke is black. Following is a diagram of a triangle with different stroke colors.

    Stroke

    Example

    We will see an example demonstrating how to colour the boundary of a 2D shape in JavaFX. In here, we are drawing a 2D shape, say a rectangle. By default, the rectangle will be coloured black; we will try to change its boundary colour to Violet. Save the file with the name StrokeExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Rectangle;importjavafx.scene.shape.Shape;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Rectangle Rectangle rectangle =newRectangle(50.0f,50.0f,200.0f,100.0f);  
    
    
      rectangle.setStroke(Color.VIOLET);
      rectangle.setStrokeWidth(7.0);//Creating a Group object  Group root =newGroup(rectangle);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Rectangle");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeExample

    Output

    On executing, the above program generates a JavaFX window displaying a rectangle with a stroke coloured violet as shown below.

    Stroke Output

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    In this example, we are drawing a polygon and change its boundary colour to RED. Save the file with the name StrokePolygonExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polygon;importjavafx.scene.shape.Shape;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokePolygonExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Polygon Polygon polygon =newPolygon();//Adding coordinates to the polygon 
    
      polygon.getPoints().addAll(newDouble&#91;]{100.0,50.0,200.0,50.0,250.0,150.0,200.0,250.0,100.0,250.0,});  
      polygon.setStroke(Color.RED);
      polygon.setStrokeWidth(5.0);//Creating a Group object  Group root =newGroup(polygon);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Polygon");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokePolygonExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokePolygonExample

    Output

    On executing, the above program generates a JavaFX window displaying a rectangle with a stroke coloured violet as shown below.

    Stroke Output
  • Stroke Fill Property

    JavaFX application supports displaying diverse content like text, 2D shapes, 3D shapes, etc.; and every object has a default setting in order to create a basic application. Hence, while drawing 2D shapes on a JavaFX application, each shape also has some default settings that can be modified when they are set separately. For instance, the default fill colour in a 2D shape is always black.

    Various properties are introduced to improve the quality of these shapes; and we have already learned how to change the dimensions and placement of the shape boundaries, in previous chapters. In this chapter, we will learn how to change the default colour black of a specific 2D shape to other colours.

    Stroke Fill Property

    Stroke Fill property in JavaFX 2D shapes is used to specify the colour which a shape is to be filled with. This property belongs to the javafx.scene.paint package. You can set the fill color of a shape using the method setFill() as follows −

    path.setFill(COLOR.BLUE);

    By default, the value of the stroke color is BLACK. Following is a diagram of a triangle with different colors.

    Stroke Fill

    Example

    In this example, we will try to create two 2D circles, and fill one of the circle with Yellow colour and another will maintain its default colour. The aim is to observe the difference between both shapes. Save this file with the name StrokeFillExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Circle;importjavafx.scene.shape.Shape;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeFillExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Circle Circle circle1 =newCircle(200.0f,150.0f,50.0f);Circle circle2 =newCircle(100.0f,150.0f,50.0f);
    
    
      circle1.setFill(Color.YELLOW);//Creating a Group object  Group root =newGroup();
      root.getChildren().addAll(circle1, circle2);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Colouring a Circle");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeFillExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeFillExample

    Output

    On executing, the above program generates a JavaFX window displaying two circles, the left one having its default fill while the other one is yellow coloured, as shown below.

    Stroke Fill Output

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    We created two simple 2D shapes in the previous example, but you can also set a fill color to complex shapes created using path element.

    In this example, we are trying to fill a complex shape created using line commands of SVG Path. Save this file with the name StrokeFillSVGPath.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.shape.SVGPath;importjavafx.stage.Stage;publicclassStrokeFillSVGPathextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a SVGPath object SVGPath svgPath =newSVGPath();String path ="M 100 100 H 190 V 190 H 150 L 200 200";//Setting the SVGPath in the form of string 
    
      svgPath.setContent(path);// Setting the stroke and fill of the path
      svgPath.setStroke(Color.BLACK);
      svgPath.setFill(Color.BLUE);//Creating a Group object  Group root =newGroup(svgPath);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage
      stage.setTitle("Drawing a Line");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeFillSVGPath.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeFillSVGPath

    Output

    On executing, the above program generates a JavaFX window displaying two circles, the left one having its default fill while the other one is yellow coloured, as shown below.

    Stroke Fill SVG Path
  • Stroke Width Property

    In the previous chapters, we have learned about various 2D shapes and how they are drawn in a JavaFX application. However, it is necessary to make your application as attractive as possible for better user experience. This also includes enhancing the look and feel of your 2D shapes within your JavaFX application.

    JavaFX provides a set of properties for this purpose. They are used to improve the quality of your shapes on the application. In this chapter, we will learn about Stroke Width property in detail.

    Stroke Width Property

    The Stroke Width Property is used to set thickness of the boundary line of a 2D shape. This property is of the type double and it represents the width of the boundary line of the shape. You can set the stroke width using the method setStrokeWidth() as follows −

    Path.setStrokeWidth(3.0)

    By default, the value of the stroke with of a shape is 1.0. Following is a diagram of a triangle with different values of stroke width.

    Stroke Width

    Example

    In this example, we will try to create a 2D shape, say a circle, and set a value to its stroke width. Save this file with the name StrokeWidthExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Circle;importjavafx.scene.shape.Shape;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeWidthExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Circle Circle circle =newCircle(150.0f,150.0f,50.0f);  
    
    
      circle.setFill(Color.WHITE);
      circle.setStroke(Color.BLACK);
      circle.setStrokeWidth(6.0);//Creating a Group object  Group root =newGroup(circle);//Creating a scene object Scene scene =newScene(root,300,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();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeWidthExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeWidthExample

    Output

    On executing, the above program generates a JavaFX window displaying a circle with a stroke width as shown below.

    Stroke Width Output

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    Now, let us try to draw a Triangle shape with relatively larger width and observe the results. Save this file with the name StrokeWidthTriangle.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polygon;importjavafx.scene.shape.Shape;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeWidthTriangleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Triangle Polygon triangle =newPolygon();//Adding coordinates to the polygon 
    
      triangle.getPoints().addAll(newDouble&#91;]{150.0,150.0,220.0,175.0,150.0,200.0,});  
      triangle.setFill(Color.WHITE);
      triangle.setStroke(Color.BLACK);
      triangle.setStrokeWidth(100.0);//Creating a Group object  Group root =newGroup(triangle);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Triangle");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved Java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeWidthTriangle.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeWidthTriangle

    Output

    On executing, the above program generates a JavaFX window displaying a triangle with a relatively larger stroke width as shown below.

    Stroke Width Output
  • Stroke Type Property

    Two dimensional(2D) shapes, in geometry, are usually referred to as structures that has only two dimensions of measure, commonly length and breadth, and lie on an XY plane. These structures can either be open or closed figures.

    Open figures include curves like Cubic curve, Quadrilateral curve, etc. whereas closed figures include all types of polygons, circles etc.

    In JavaFX, these 2D shapes can be drawn on an application by importing the javafx.scene.shape package. However, to improve the quality of a shape, there are various properties and operations that can be performed on it.

    In this chapter, we will learn about Stroke Type property in detail.

    Stroke Type Property

    The Stroke Type property of 2D shapes is used to specify the type of boundary line a 2D shape must have. In JavaFX, this property is set using the StrokeType class. You can set the type of the stroke using the method setStrokeType() as follows −

    Path.setStrokeType(StrokeType.stroke_type);

    The stroke_type of a shape can be −

    • Inside − The boundary line will be drawn inside the edge (outline) of the shape (StrokeType.INSIDE).
    • Outside − The boundary line will be drawn outside the edge (outline) of the shape (StrokeType.OUTSIDE).
    • Centered − The boundary line will be drawn in such a way that the edge (outline) of the shape passes exactly thorough the center of the line (StrokeType.CENTERED).

    By default, the stroke type of a shape is centered. Following is the diagram of a triangle with different Stroke Types −

    Stroke Type

    Example

    Let us see an example demonstrating the usage of StrokeType property on a 2D shape. Save this file with the name StrokeTypeExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polygon;importjavafx.scene.shape.StrokeType;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeTypeExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Triangle Polygon triangle =newPolygon();//Adding coordinates to the polygon 
    
      triangle.getPoints().addAll(newDouble&#91;]{100.0,50.0,170.0,150.0,100.0,250.0,});
      triangle.setFill(Color.BLUE);
      triangle.setStroke(Color.BLACK);
      triangle.setStrokeWidth(7.0);
      triangle.setStrokeType(StrokeType.CENTERED);//Creating a Group object  Group root =newGroup(triangle);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Triangle");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeTypeExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeTypeExample

    Output

    On executing, the above program generates a JavaFX window displaying a triangle with centered stroke type as shown below.

    Stroke Type Output

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Example

    Let us see an example demonstrating the usage of INSIDE StrokeType property on a 2D shape. We are using a larger width here in order to properly show the difference between INSIDE and CENTERED stroke types from previous example. Save this file with the name StrokeTypeEllipse.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Ellipse;importjavafx.scene.shape.StrokeType;importjavafx.scene.paint.Color;importjavafx.stage.Stage;publicclassStrokeTypeEllipseextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing an ellipse Ellipse ellipse =newEllipse();//Setting the properties of the ellipse 
    
      ellipse.setCenterX(150.0f); 
      ellipse.setCenterY(100.0f); 
      ellipse.setRadiusX(100.0f); 
      ellipse.setRadiusY(50.0f); 
      ellipse.setFill(Color.ORANGE);
      ellipse.setStroke(Color.BLACK);
      ellipse.setStrokeWidth(20.0);
      ellipse.setStrokeType(StrokeType.INSIDE);//Creating a Group object  Group root =newGroup(ellipse);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Ellipse");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeTypeEllipse.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrokeTypeEllipse

    Output

    On executing, the above program generates a JavaFX window displaying a triangle with centered stroke type as shown below.

    Stroke Type Output
  • Drawing an SVGPath

    SVG (Scalable Vector Graphics) is an XML based language to define vector based graphics. The <path> element in the SVG library is the most powerful while drawing basic shapes. Using paths, you can draw lines, curves, arcs, and also various complex shapes including them.

    Even though a path is similar to the polyline element while creating complex shapes, the scale of complex shapes drawn using a polyline element is not larger than shapes drawn using path element.

    path in SVG is defined by only one parameter. This parameter holds series of commands, like line, curve or arc commands. And each of these commands are instantiated using a single letter; for example, the letter ‘M’ calls the “Move To” command, the letter ‘L’ calls the “line” command and ‘C’ calls “Curve” command. And these letters can either be specified as either a lowercase or an uppercase letter. The lowercase letter specifies relative coordinates, while the uppercase letter specifies absolute coordinates.

    The same concept of SVGPath is adopted by JavaFX, in order to create objects.

    SVG Path in JavaFX

    In JavaFX we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape.

    By instantiating this class, you can create a node which is created by parsing an SVG path in JavaFX.

    This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.

    To draw a shape by parsing an SVG path, you need to pass values to this property, using the method named setContent() of this class as follows −

    setContent(value);

    Steps to Draw SVGPath

    To Draw a shape by parsing an SVGPath in JavaFX, follow the steps given below.

    Step 1: Creating an Object of the SVGPath Class

    You can create a required shape in JavaFX by parsing an SVGPath. To do so, instantiate the class named SVGPath which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method as follows.

    publicclassClassNameextendsApplication{publicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class SVGPath         SVGPath svgpath =newSVGPath();}}

    Step 2: Setting the SVGPath

    Set the content for the SVG object using the method setContent(). To this method, you need to pass the SVGPath. Using which, a shape should be drawn in the form of a string as shown in the following code block.

    String path ="M 100 100 L 300 100 L 200 300 z";//Setting the SVGPath in the form of string 
    svgPath.setContent(path);

    Step 3: Adding SVGPath to Group

    In the start() method, instantiate the Group class by passing the SVGPath object as a parameter value to its constructor −

    Group root =newGroup(svgpath);

    Step 4: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates a 2D shape constructed with lines by parsing SVG path using JavaFX. Save this code in a file with the name SVGExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.SVGPath;importjavafx.stage.Stage;publicclassSVGExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a SVGPath object SVGPath svgPath =newSVGPath();String path ="M 100 100 L 300 100 L 200 300 z";//Setting the SVGPath in the form of string 
    
      svgPath.setContent(path);//Creating a Group object  Group root =newGroup(svgPath);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage
      stage.setTitle("Drawing a Triangle");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls SVGExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls SVGExample

    Output

    On executing, the above program generates a JavaFX window displaying a triangle, which is drawn by parsing the SVG path as shown below.

    Drawing Sphere

    Example

    You can also construct complex shapes from curves and arcs using an SVG path. Following example creates a cubic curve using an SVG Path. Save this code in a file with the name SVGCurveExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.shape.SVGPath;importjavafx.stage.Stage;publicclassSVGCurveExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a SVGPath object SVGPath svgPath =newSVGPath();String path ="M 70 110 C 70 180, 210 180, 210 110";//Setting the SVGPath in the form of string 
    
      svgPath.setContent(path);// Setting the stroke and fill of the path
      svgPath.setStroke(Color.BLACK);
      svgPath.setFill(Color.ORANGE);//Creating a Group object  Group root =newGroup(svgPath);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage
      stage.setTitle("Drawing a Bezier Curve");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls SVGCurveExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls SVGCurveExample

    Output

    On executing, the above program generates a JavaFX window displaying a triangle, which is drawn by parsing the SVG path as shown below.

    Drawing Sphere
  • Drawing an Arc

    An arc in simple geometry is defined as a portion of a circumference of an ellipse or a circle. Or, simply put, it is a curve that is joins two end points. An arc also encloses an angle less than or equal to 360 degrees at the centre of the circle. It is described by the following properties −

    • length − The distance along the arc.
    • angle − The angle the curve makes at the centre of the circle.
    • radiusX − The width of the full Ellipse of which the current arc is a part of.
    • radiusY − The height of the full Ellipse of which the current arc is a part of.

    If both radiusX and radiusY are same, then the arc is a part of a circle circumference.

    ARC

    Arc in JavaFX

    In JavaFX, an arc is represented by a class named Arc. This class belongs to the package javafx.scene.shape.

    By instantiating this class, you can create an arc node in JavaFX.

    This class has a few properties of the double datatype namely −

    • centerX − The x coordinate of the center of the arc.
    • centerY − The y coordinate of the center of the arc.
    • radiusX − The width of the full ellipse of which the current arc is a part of.
    • radiusY − The height of the full ellipse of which the current arc is a part of.
    • startAngle − The starting angle of the arc in degrees.
    • length − The angular extent of the arc in degrees.

    To draw an arc, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, or, by using their respective setter methods.

    Types of Arc

    In JavaFX, you can draw three kinds of arc’s namely −

    • Open − An arc which is not closed at all is known as an open arc.
    • Chord − A chord is a type of an arc which is closed by straight line.
    • Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse.
    Open Closed Round

    You can set the type of the arc using the method setType() by passing any of the following properties − ArcType.OPEN, ArcType.CHORD, ArcType.Round.

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Steps to Draw Arc

    To Draw an arc in JavaFX, follow the steps given below.

    Step 1: Creating an Arc

    You can create an arc in JavaFX by instantiating the class named Arc which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method of Application class as shown below.

    publicclassClassNameextendsApplication{publicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class Arc         Arc arc =newArc();}}

    Step 2: Setting Properties to the Arc

    Specify the x, y coordinates of the center of the Ellipse (of which this arc is a part of). These coordinates include – radiusX, radiusY, start angle and length of the arc using their respective setter methods as shown in the following code block.

    //Setting the properties of the arc 
    arc.setCenterX(300.0f); 
    arc.setCenterY(150.0f); 
    arc.setRadiusX(90.0f); 
    arc.setRadiusY(90.0f); 
    arc.setStartAngle(40.0f); 
    arc.setLength(239.0f);

    Step 3: Setting the Type of the Arc

    You can also set the type of the arc (round, chord open) by using the setType() method as shown in the following code block.

    //Setting the type of the arc 
    arc.setType(ArcType.ROUND);

    Step 4: Adding Arc Object to Group

    In the start() method, instantiate a Group class by passing the arc object, which was created in the previous step, as a parameter value to its constructor −

    Group root =newGroup(arc);

    Step 5: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates an arc. Save this code in a file with the name ArcExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.Arc;importjavafx.scene.shape.ArcType;publicclassArcExampleextendsApplication{publicvoidstart(Stage stage){//Drawing an arc Arc arc =newArc();//Setting the properties of the arc 
    
      arc.setCenterX(300.0f); 
      arc.setCenterY(150.0f); 
      arc.setRadiusX(90.0f); 
      arc.setRadiusY(90.0f); 
      arc.setStartAngle(40.0f); 
      arc.setLength(239.0f);//Setting the type of the arc 
      arc.setType(ArcType.ROUND);//Creating a Group object  Group root =newGroup(arc);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing an Arc");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved Java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls ArcExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ArcExample

    Output

    On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot.

    Drawing Arc

    Example

    Let us try to draw another arc of type "Open" in the following example. Save this code in a file with the name ArcOpen.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.Arc;importjavafx.scene.shape.ArcType;publicclassArcOpenextendsApplication{publicvoidstart(Stage stage){//Drawing an arc Arc arc =newArc();//Setting the properties of the arc 
    
      arc.setCenterX(300.0f); 
      arc.setCenterY(150.0f); 
      arc.setRadiusX(90.0f); 
      arc.setRadiusY(90.0f); 
      arc.setStartAngle(40.0f); 
      arc.setLength(239.0f);//Setting the type of the arc 
      arc.setType(ArcType.OPEN);//Creating a Group object  Group root =newGroup(arc);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing an Open Arc");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved Java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls ArcOpen.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ArcOpen

    Output

    On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot.

    Drawing Open Arc

    Example

    Now we will try to draw another arc of type "Chord" in the following example. Save this code in a file with the name ArcChord.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.Arc;importjavafx.scene.shape.ArcType;publicclassArcChordextendsApplication{publicvoidstart(Stage stage){//Drawing an arc Arc arc =newArc();//Setting the properties of the arc 
    
      arc.setCenterX(300.0f); 
      arc.setCenterY(150.0f); 
      arc.setRadiusX(90.0f); 
      arc.setRadiusY(90.0f); 
      arc.setStartAngle(40.0f); 
      arc.setLength(239.0f);//Setting the type of the arc 
      arc.setType(ArcType.CHORD);//Creating a Group object  Group root =newGroup(arc);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Chord Arc");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved Java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls ArcChord.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ArcChord

    Output

    On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot.

    Drawing Chord Arc
  • Drawing a Quad Curve

    Mathematically, a quadratic curve is one that is described by a quadratic function like − y = ax2 + bx + c.

    In computer graphics Bezier curves are used. These are parametric curves which appear reasonably smooth at all scales. These Bezier curves are drawn based on points on an XY plane.

    A quadratic curve is a Bezier parametric curve in the XY plane which is a curve of degree 2. It is drawn using three points: start point, end point and control point as shown in the following diagram

    Quadcurve

    Quad Curve in JavaFX

    In JavaFX, a Quad Curve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape.

    By instantiating this class, you can create a QuadCurve node in JavaFX.

    This class has 6 properties of the double datatype namely −

    • startX − The x coordinate of the starting point of the curve.
    • startY − The y coordinate of the starting point of the curve.
    • controlX − The x coordinate of the control point of the curve.
    • controlY − The y coordinate of the control point of the curve.
    • endX − The x coordinate of the end point of the curve.
    • endY − The y coordinate of the end point of the curve.

    To draw a Quad Curve, you need to pass values to these properties. This can be done either by passing them to the constructor of this class, in the same order, at the time of instantiation; or by using appropriate setter methods.

    Steps to Draw Quad Curve

    To Draw a Bezier Quadrilateral Curve in JavaFX, follow the steps given below.

    Step 1: Creating a Quad Curve

    You can create a Quad Curve in JavaFX by instantiating the class named QuadCurve which belongs to a package javafx.scene.shape. You can then instantiate this class in start() method of Application class as shown in the following code block.

    publicclassClassNameextendsApplication{publicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class QuadCurve QuadCurve quadcurve =newQuadCurve();}}

    Step 2: Setting Properties to the Quad Curve

    Specify the x, y coordinates of the three points: start point, end point and control points, of the required curve, using their respective setter methods as shown in the following code block.

    //Adding properties to the Quad Curve 
    quadCurve.setStartX(100.0); 
    quadCurve.setStartY(220.0f); 
    quadCurve.setEndX(500.0f); 
    quadCurve.setEndY(220.0f);
    quadCurve.setControlX(250.0f); 
    quadCurve.setControlY(0.0f);

    Or, by using their respective setter methods as follows −

    QuadCurve quadcurve =newQuadCurve(startX, startY, controlX, controlY, endX, endY);

    Step 3: Adding Quad Curve Object to Group

    In the start() method, instantiate a Group class by passing the previously created QuadCurve object as a parameter value to its constructor −

    Group root =newGroup(quadcurve);

    Step 4: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates a quadrilateral curve using JavaFX. Save this code in a file with the name QuadCurveExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.QuadCurve;publicclassQuadCurveExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a QuadCurve QuadCurve quadCurve =newQuadCurve();//Adding properties to the Quad Curve 
    
      quadCurve.setStartX(100.0); 
      quadCurve.setStartY(220.0f); 
      quadCurve.setEndX(500.0f); 
      quadCurve.setEndY(220.0f); 
      quadCurve.setControlX(250.0f); 
      quadCurve.setControlY(0.0f);//Creating a Group object  Group root =newGroup(quadCurve);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Quad curve");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveExample

    Output

    On executing, the above program generates a JavaFX window displaying a Bezier quadrilateral curve as shown in the following screenshot.

    Drawing Quadcurve

    Example

    Now, you can also draw this quadrilateral curve by applying any effect, say bloom effect, as shown in the example below. Save the code in a file named QuadCurveEffect.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.effect.Bloom;importjavafx.stage.Stage;importjavafx.scene.paint.Color;importjavafx.scene.shape.QuadCurve;publicclassQuadCurveEffectextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a QuadCurve QuadCurve quadCurve =newQuadCurve();//Adding properties to the Quad Curve 
    
      quadCurve.setStartX(100.0); 
      quadCurve.setStartY(220.0f); 
      quadCurve.setEndX(300.0f); 
      quadCurve.setEndY(220.0f); 
      quadCurve.setControlX(250.0f); 
      quadCurve.setControlY(0.0f);
    quadCurve.setFill(Color.RED);//Instantiating the Bloom class Bloom bloom =newBloom();//setting threshold for bloom
      bloom.setThreshold(0.1);//Applying bloom effect to quadCurve 
      quadCurve.setEffect(bloom);//Creating a Group object  Group root =newGroup(quadCurve);//Creating a scene object Scene scene =newScene(root,400,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Quad curve");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveEffect.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveEffect

    Output

    On executing, the above program generates a JavaFX window displaying a Bezier quadrilateral curve as shown in the following screenshot.

    Drawing Vertical Quadcurve
  • Drawing a Cubic Curve

    A Cubic Curve is described by a third-degree polynomial function of two variables, and can be written in the following form −

    CubicCurve

    These Bezier curves are generally used in computer graphics. They are parametric curves which appear reasonably smooth at all scales. These curves are drawn based on points on the XY plane.

    A cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. It is drawn using four points − Start Point, End Point, Control Point and Control Point2 as shown in the following diagram.

    Bezier Curves

    Cubic Curve in JavaFX

    In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape.

    By instantiating this class, you can create a CubicCurve node in JavaFX.

    This class has 8 properties of the double datatype namely −

    • startX − The x coordinate of the starting point of the curve.
    • startY − The y coordinate of the starting point of the curve.
    • controlX1 − The x coordinate of the first control point of the curve.
    • controlY1 − The y coordinate of the first control point of the curve.
    • controlX2 − The x coordinate of the second control point of the curve.
    • controlY2 − The y coordinate of the second control point of the curve.
    • endX − The x coordinate of the end point of the curve.
    • endY − The y coordinate of the end point of the curve.

    To draw a cubic curve, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, or by using their respective setter methods.

    Steps to Draw Cubic Curve

    To draw a Bezier cubic curve in JavaFX, follow the steps given below.

    Step 1: Creating a Cubic Curve

    You can create a Cubic Curve in JavaFX by instantiating the class named CubicCurve which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method of Application class as follows.

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class CubicCurve         CubicCurve cubiccurve =newCubicCurve();}}

    Step 2: Setting Properties to the Cubic Curve

    Specify the x, y coordinates of the four points: start point, end point, control point1 and control point2 of the required curve, using their respective setter methods as shown in the following code block.

    //Setting properties to cubic curve 
    cubicCurve.setStartX(100.0f); 
    cubicCurve.setStartY(150.0f); 
    cubicCurve.setControlX1(400.0f); 
    cubicCurve.setControlY1(40.0f); 
    cubicCurve.setControlX2(175.0f); 
    cubicCurve.setControlY2(250.0f); 
    cubicCurve.setEndX(500.0f); 
    cubicCurve.setEndY(150.0f);

    Step 3: Adding Cubic Curve to Group

    Instantiate a Group class in the start() method by passing the previously created CubicCurve object as a parameter to its constructor.

    Group root =newGroup(cubiccurve);

    Step 4: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates a Bezier CubicCurve using JavaFX. Save this code in a file with the name CubicCurveExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.CubicCurve;publicclassCubicCurveExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a cubic curve CubicCurve cubicCurve =newCubicCurve();//Setting properties to cubic curve
    
      cubicCurve.setStartX(100.0f); 
      cubicCurve.setStartY(150.0f); 
      cubicCurve.setControlX1(400.0f); 
      cubicCurve.setControlY1(40.0f); 
      cubicCurve.setControlX2(175.0f); 
      cubicCurve.setControlY2(250.0f); 
      cubicCurve.setEndX(500.0f); 
      cubicCurve.setEndY(150.0f);//Creating a Group object  Group root =newGroup(cubicCurve);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a cubic curve");//Adding scene to the stage
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveExample

    Output

    On executing, the above program generates a JavaFX window displaying a Bezier cubic curve as shown below.

    Drawing Cubic Curve

    Example

    In the following example, we are trying to apply the DropShadow effect on a Cubic Curve drawn. Save this code in a file with the name CubicCurveEffect.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.effect.DropShadow;importjavafx.stage.Stage;importjavafx.scene.paint.Color;importjavafx.scene.shape.CubicCurve;publicclassCubicCurveEffectextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a cubic curve CubicCurve cubicCurve =newCubicCurve();//Setting properties to cubic curve
    
      cubicCurve.setStartX(50.0f); 
      cubicCurve.setStartY(100.0f); 
      cubicCurve.setControlX1(200.0f); 
      cubicCurve.setControlY1(40.0f); 
      cubicCurve.setControlX2(150.0f); 
      cubicCurve.setControlY2(200.0f); 
      cubicCurve.setEndX(200.0f); 
      cubicCurve.setEndY(50.0f);
    cubicCurve.setFill(Color.RED);//Instantiating the DropShadow class DropShadow ds =newDropShadow();//Applying DropShadow effect to cubicCurve
      cubicCurve.setEffect(ds);//Creating a Group object  Group root =newGroup(cubicCurve);//Creating a scene object Scene scene =newScene(root,300,300);//Setting title to the Stage 
      stage.setTitle("Drawing a cubic curve");//Adding scene to the stage
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveEffect.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveEffect

    Output

    On executing, the above program generates a JavaFX window displaying a Bezier cubic curve as shown below.

    Drawing Cubic Curve
  •  Drawing a Polyline

    Polyline is defined as a continuous structure that is formed by combining multiple line segments with some vertices. These vertices are addressed as endpoints. Thus, a polyline can be constructed by specifying these endpoints through which these line segments are to be drawn.

    It consists of various properties like Points, width, color, start and end caps, type of join, stroke pattern etc. A Polyline is same as a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments.

    In short, we can say a polygon is an open figure formed by coplanar line segments.

    Polyline

    Polyline in JavaFX

    In JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape..

    By instantiating this class, you can create polyline node in JavaFX. You need to pass the x, y coordinates of the points by which the polyline should be defined in the form of a double array.

    You can pass the double array as a parameter of the constructor of this class as shown below −

    Polyline polyline =newPolyline(doubleArray);

    Or, by using the getPoints() method as follows −

    polyline.getPoints().addAll(newDouble[]{List of XY coordinates separated by commas });

    Steps to Draw Polyline

    To Draw a Polyline in JavaFX, follow the steps given below.

    Step 1: Creating a Polyline

    You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape. You can instantiate this class in start() method as follows.

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class Polyline Polyline polyline =newPolyline();}}

    Step 2: Setting Properties to the Polyline

    Specify a double array holding the XY coordinates of the points of the required polyline (hexagon in this example) separated by commas. You can do this by using the getPoints() method of the Polyline class as shown in the following code block.

    //Adding coordinates to the hexagon 
    polyline.getPoints().addAll(newDouble[]{200.0,50.0,400.0,50.0,450.0,150.0,400.0,250.0,200.0,250.0,150.0,150.0,});

    Step 3: Adding Polyline Object to Group

    In the start() method, instantiate the class named Group, which belongs to the package javafx.scene, by passing the Polyline object, created in the previous step, as a parameter value to its constructor.

    Group root =newGroup(polyline);

    Step 4: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates a polyline using JavaFX. Save this code in a file with the name PolylineExample1.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.PolylinepublicclassPolylineExample1extendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a polyline Polyline polyline =newPolyline();//Adding coordinates to the polygon 
    
      polyline.getPoints().addAll(newDouble&#91;]{200.0,50.0,400.0,50.0,450.0,150.0,400.0,250.0,200.0,250.0,150.0,150.0,});//Creating a Group object  Group root =newGroup(polyline);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Polyline");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls PolylineExample1.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls PolylineExample1

    Output

    On executing, the above program generates a JavaFX window displaying a polyline as shown below.

    Drawing Polyine

    Example

    In this example, let us try to draw a polyline of 4 vertices. You can save the file name as PolylineExample2.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polyline;importjavafx.stage.Stage;publicclassPolylineExample2extendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Polyline Polyline polyline =newPolyline();//Adding coordinates to the polygon 
    
      polyline.getPoints().addAll(newDouble&#91;]{300.0,50.0,450.0,150.0,300.0,250.0,150.0,150.0,});//Creating a Group object  Group root =newGroup(polyline);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Polyline");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls PolylineExample2.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls PolylineExample2

    Output

    On executing, the above program generates a JavaFX window displaying a 4 vertices Polyline as shown below.

    Drawing Polyline
  • Drawing a Polygon

    Polygon is geometrically defined as a closed shape formed by a number of coplanar line segments connected from end to end. The name “polygon” is derived from the Greek words, “poly” meaning “many” and “gonia” meaning “angles”.

    A polygon is described by two parameters, namely, the length of its sides and the measures of its interior angles.

    There are various types of Polygons based on the numbers of sides and angles. They are listed below −

    • If a polygon has three sides, then it is referred to as a triangle.
    • If a polygon has four sides, then it is known as quadrilateral. Shapes like rectangles, squares, parallelogram etc., are all types of quadrilaterals.
    • If a polygon has five sides, then it is known as a pentagon. Similarly, the polygon with six sides is called hexagon, seven sides is heptagon, eight sides is octagon etc.
    Polygon

    Polygon in JavaFX

    In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape.

    By instantiating this class, you can create a polygon node in JavaFX. You need to pass the x, y coordinates of the points by which the polygon should be defined in the form of a double array.

    You can pass the double array as a parameter of the constructor of this class as shown below −

    Polygon polygon =newPolygon(doubleArray);

    Or, by using the getPoints() method as follows −

    polygon.getPoints().addAll(newDouble[]{List of XY coordinates separated by commas });

    Steps to Draw Polygon

    To draw a polygon in JavaFX, follow the steps given below.

    Step 1: Creating a Polygon

    Create a polygon in JavaFX by instantiating the class named Polygon which belongs to a package javafx.scene.shape within the start() method. You can instantiate this class as follows.

    publicclassClassNameextendsApplication{publicvoidstart(Stage primaryStage)throwsException{//Creating an object of the class Polygon Polygon hexagon =newPolygon();}}

    Step 2: Setting Properties to the Polygon

    Specify a double array holding the XY coordinates of the points of the required polygon (hexagon in this example) separated by commas, using the getPoints() method of the Polygon class, as follows.

    //Adding coordinates to the hexagon 
    hexagon.getPoints().addAll(newDouble[]{200.0,50.0,400.0,50.0,450.0,150.0,400.0,250.0,200.0,250.0,150.0,150.0,})

    Step 3: Adding Polygon Object to Group

    In the start() method, instantiate the class named Group, which belongs to the package javafx.scene, by passing the Polygon object, created in the previous step, as a parameter value to its constructor.

    Group root =newGroup(hexagon);

    Step 4: Launching Application

    Once the 2D object is created, follow the given steps below to launch the application properly −

    • Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters.
    • Then, set the title to the stage using the setTitle() method of the Stage class.
    • Now, a Scene object is added to the stage using the setScene() method of the class named Stage.
    • Display the contents of the scene using the method named show().
    • Lastly, the application is launched with the help of the launch() method.

    Example

    Following is a program which generates a Polygon (hexagon) using JavaFX. Save this code in a file with the name PolygonExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polygon;importjavafx.stage.Stage;publicclassPolygonExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Polygon Polygon polygon =newPolygon();//Adding coordinates to the polygon 
    
      polygon.getPoints().addAll(newDouble&#91;]{200.0,50.0,400.0,50.0,450.0,150.0,400.0,250.0,200.0,250.0,150.0,150.0,});//Creating a Group object  Group root =newGroup(polygon);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Polygon");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls PolygonExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls PolygonExample

    Output

    On executing, the above program generates a JavaFX window displaying a polygon as shown below.

    Drawing Polygon

    Example

    Now, let us try to draw polygons other than a hexagon, say a rhombus. Save this code in a file with the name RhombusExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.shape.Polygon;importjavafx.stage.Stage;publicclassRhombusExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Polygon Polygon polygon =newPolygon();//Adding coordinates to the polygon 
    
      polygon.getPoints().addAll(newDouble&#91;]{300.0,50.0,450.0,150.0,300.0,250.0,150.0,150.0,});//Creating a Group object  Group root =newGroup(polygon);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Polygon");//Adding scene to the stage 
      stage.setScene(scene);//Displaying the contents of the stage 
      stage.show();}publicstaticvoidmain(String args&#91;]){launch(args);}}</code></pre>

    Compile and execute the saved java file from the command prompt using the following commands.

    javac --module-path %PATH_TO_FX%--add-modules javafx.controls RhombusExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls RhombusExample

    Output

    On executing, the above program generates a JavaFX window displaying a rhombus as shown below.

    Drawing Rhombus