Author: saqibkhan

  • Effects

    An effect is any action that enhances the appearance of the graphics. In JavaFX, an effect is an algorithm that is applied on nodes to enhance their appearance visually. The effect property of the Node class is used to specify the effect.

    In JavaFX, you can set various effects to a node such as bloom, blur and glow. Each of these effects are represented by a class and all these classes are available in a package named javafx.scene.effect.

    Applying Effects to a Node

    You can apply an effect to a node using the setEffect() method. To this method, you need to pass the object of the effect.

    To apply an effect to a node, you need to −

    • Create the node.
    • Instantiate the respective class of the effect that is needed to be applied.
    • Set the properties of the effect.
    • Apply the effect to the node using the setEffect() method.

    Creating the Nodes

    First of all, create the nodes in a JavaFX application by instantiating their respective classes.

    For example, if you want to apply glow effect to an image in your application. Firstly, you need to create an image node by instantiating the Image class and set its view as shown below.

    Example

    //Creating an image Image image =newImage("https://www.tutorialspoint.com/green/images/logo.png");//Setting the image view ImageView imageView =newImageView(image);//Setting the position of the image 
    imageView.setX(100); 
    imageView.setY(70);//setting the fit height and width of the image view 
    imageView.setFitHeight(200);
    imageView.setFitWidth(400);//Setting the preserve ratio of the image view 
    imageView.setPreserveRatio(true);

    Instantiating the Respective Class

    Instantiate the class representing the effect that is needed to be applied to the created node.

    For example − To apply the glow effect, you need to instantiate the Glow class as shown in the following code box −

    Glow glow =newGlow();

    Setting the Properties of the Effect

    After instantiating the class, you need to set the properties for the effect using its setter methods.

    For example − To draw a 3-Dimensional box, you need to pass its width, height and depth. You can specify these values using their respective setter methods as shown below −

    //setting the level property 
    glow.setLevel(0.9);

    Adding Effect to the Node

    Finally, you can apply the required effect to the node using the setEffect() method. For example: To set the glow effect to the image node, you need to pass the object of the Glow class to this method as follows −

    imageView.setEffect(glow);

    Types of JavaFX Effects

    The following table gives you the list of various effects (classes) provided by JavaFX. These classes exist in the package called javafx.scene.effect.

    S.NoEffect and Description
    1Color AdjustYou can adjust the color of an image by applying the color adjust effect to it. This includes the adjustment of the hue, saturation, brightness and contrast on each pixelThe class named ColorAdjust of the package javafx.scene.effect represents the color adjust effect.
    2Color InputColor Input Effect gives the same output as drawing a rectangle and filling it with color. Unlike other effects, if this effect is applied to any node, it displays only a rectangular box (not the node). This effect is mostly used to pass as an input for other effects.The class named ColorInput of the package javafx.scene.effect represents the color input effect.
    3Image InputImage input effect in JavaFX just embeds an image to the JavaFX screen.Just like Color Input effect (It is used to pass the specified colored rectangular region as input to other effect), Image Input effect is used to pass the specified image as an input to another effect.The class named ImageInput of the package javafx.scene.effect represents the Image Input effect.
    4BlendIn general, blend means mixture of two or more different things or substances. If we apply this blend effect, it takes the pixels of two different inputs, at the same location and it produces a combined output based on the blend mode.The class named Blend of the package javafx.scene.effect represents the blend effect.
    5BloomOn applying bloom effect, pixels in some portions of the node are made to glow.The class named Bloom of the package javafx.scene.effect represents the bloom effect.
    6GlowJust like bloom, the Glow effect makes the given input image to glow, this effect makes the bright pixels of the input brighter.The class named Glow of the package javafx.scene.effect represents the glow effect.
    7Box BlurOn applying this blur effect to a node, it is made unclear. Box blur is a kind of blur effect provided by JavaFX. In this effect, when we apply blur to a node, a simple box filter is used.The class named BoxBlur of the package javafx.scene.effect represents the boxblur effect.
    8GaussianBlurJust like Box Blur Gaussian is an effect to blur the nodes in JavaFX. The only difference in the Gaussian Blur effect is that a Gaussian convolution kernel is used to produce a blurring effect.The class named GaussianBlur of the package javafx.scene.effect represents the Gaussian Blur effect.
    9MotionBlurJust like Gaussian Effects, Motion Blur is an effect to blur the nodes in JavaFX. It also uses a Gaussian convolution kernel to produce a blurring effect, but the difference is in this effect the Gaussian convolution kernel is used with a specified angle.The class named MotionBlur of the package javafx.scene.effect represents the Motion Blur effect.
    10ReflectionOn applying the reflection effect to a node in JavaFX, a reflection of it is added at the bottom of the node.The class named Reflection of the package javafx.scene.effect represents the reflection effect.
    11SepiaToneOn applying the Sepia tone effect to a node in JavaFX (image in general), it is toned with a reddish brown color.The class named SepiaTone of the package javafx.scene.effect represents the sepia tone effect.
    12ShadowThis effect creates a duplicate of the specified node with blurry edges.The class named Shadow of the package javafx.scene.effect represents the sepia tone effect.
    13DropShadowOn applying this effect to a node, a shadow will be created behind the specified node.The class named DropShadow of the package javafx.scene.effect represents the drop shadow effect.
    14InnerShadowOn applying this effect to a node, a shadow will be created inside the edges of the node.The class named InnerShadow of the package javafx.scene.effect represents the inner shadow effect.
    15LightingThe lighting effect is used to simulate a light from a light source. There are different kinds of light sources namely pointdistant and spot.The class named Lighting of the package javafx.scene.effect represents the lighting effect.
    16Light.DistantOn applying this effect to a node, a light is simulated on it, as if it is being generated by a distant light source.Distant Light Source − A source which is at a far distance from the node. In here, the light is attenuated in one direction from the source.The class named Light.Distant of the package javafx.scene.effect represents the distant light source.
    17Light.SpotOn applying this effect to a node, a light is simulated on it, as if it is being generated by a spot light.Spot light Source − The light from this source attenuates in all directions. The intensity of the light depends on the distance of the object from the source.The class named Light.Spot of the package javafx.scene.effect represents the distant light source.
    18Point.SpotOn applying this effect to a node, a light is simulated on it, as if it is being generated by a point light source.Point Light Source − The light from this source attenuates in all directions from a single point. The intensity of the light depends on the distance of the object from the source.The class named Point.Spot of the package javafx.scene.effect represents the point light.
  • Text

    A JavaFX application can consist of a lot of elements including all kinds of media like images, videos, GIFs, and all dimensional shapes, text, etc. This is to improve the quality of user experience with the application. All these elements are represented by nodes on a JavaFX scene graph.

    Previously, we have learned how to create both 2D and 3D shapes. But you can also create a Text element in JavaFX applications. The Text element is represented by a separate node and it can be altered with respect to its font, size, color, and some other properties.

    In this chapter, we will learn how to display a Text node on an application using JavaFX.

    JavaFX Text Node

    The text node in JavaFX is represented by the class named Text, which belongs to the package javafx.scene.text.

    This class contains several properties to create text in JavaFX and modify its appearance. This class also inherits the Shape class which belongs to the package javafx.scene.shape.

    Therefore, in addition to the properties of the text like font, alignment, line spacing, text, etc. It also inherits the basic shape node properties such as strokeFillstrokestrokeWidthstrokeType etc.

    Creating a Text Node

    Since the class Text of the package javafx.scene.text represents the text node in JavaFX, you can create a text by instantiating this class as follows −

    Text text =newText();

    The class Text contains a property named text of string type, which represents the text that is to be created.

    After instantiating the Text class, you need to set value to this property using the setText() method as shown below.

    String text ="Hello how are you"Text.setText(text);

    You can also set the position (origin) of the text by specifying the values to the properties x and y using their respective setter methods namely setX() and setY() as shown in the following code block −

    text.setX(50); 
    text.setY(50);

    Example

    The following program is an example demonstrating how to create a text node in JavaFX. Save this code in a file with name TextExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.Text;publicclassTextExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();//Setting the text to be added. 
    
      text.setText("Hello how are you");//setting the position of the text 
      text.setX(50); 
      text.setY(50);//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Sample Application");//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 TextExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls TextExample

    Output

    On executing, the above program generates a JavaFX window displaying the specified text as follows −

    Sample Application Text

    Example

    Let us see another example where we are trying to create a text node by applying various properties like Font, size, alignment, etc. on the said text. Save this code in a file with name TextExample1.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.*;publicclassTextExample1extendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();
    
      text.setFont(newFont(20));
      text.setWrappingWidth(200);
      text.setTextAlignment(TextAlignment.JUSTIFY);
      text.setText("This is Paragraph 1\nThis is Paragraph 2");//setting the position of the text
      text.setX(50); 
      text.setY(130);//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Sample Application");//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 TextExample1.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls TextExample1

    Output

    On executing, the above program generates a JavaFX window displaying the specified text as follows −

    Sample Application Text

    Position & Font of a Text node

    You can also add a Text Node in a JavaFX application. However, any text that can be added has some default values set to it, like the size of text, font, and its color (which is black). However, it becomes necessary to change the default values, as they are not suitable for all scenarios.

    For instance, the default position of a text node in JavaFX application starts from the beginning of the screen. But, when the text content is longer and it goes out of display range, there arises a need to change its position to display all the content properly.

    Changing the position and font of text will also allow the user to develop an application as per their own requirements.

    The setFont() Method

    You can change the font size and color of the text using the setFont() method. This method accepts an object of the Font class.

    The class named Font of the package javafx.scene.text is used to define the font for the text. This class contains a static method named font().

    This method accepts four parameters namely −

    • family − This is of a String type and represents the family of the font that we want to apply to the text.
    • weight − This property represents the weight of the font. It accepts 9 values, which are − FontWeight.BLACK, FontWeight.BOLD, FontWeight.EXTRA_BOLD, FontWeight.EXTRA_LIGHT, LIGHT, MEDIUM, NORMAL, SEMI_BOLD, THIN.
    • posture − This property represents the font posture (regular or italic). It accepts two values FontPosture.REGULAR and FontPosture.ITALIC.
    • size − This property is of type double and it represents the size of the font.

    You can set font to the text by using the following method −

    text.setFont(Font.font("verdana",FontWeight.BOLD,FontPosture.REGULAR,20));

    Example

    Before trying to set the desired position and font, let us see a program with default properties of a text node in a JavaFX application.

    Save this code in a file with the name TextDefault.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.*;publicclassTextDefaultextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();//Setting the text to be added. 
    
      text.setText("Hi how are you");//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Default text");//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 TextDefault.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls TextDefault
    Output

    On executing, the above program generates a JavaFX window displaying the text with its default properties.

    Default Values Of Text

    As you can see, the text is not correctly displayed within the application, hence, prompting the need for setting position and font properties.

    Example

    The following program is an example demonstrating how to set font of the text node in JavaFX. In here, we are setting the font to Verdana, weight to bold, posture to regular and size to 20.

    Save this code in a file with the name TextFontExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.Font;importjavafx.scene.text.FontPosture;importjavafx.scene.text.FontWeight;importjavafx.scene.text.Text;publicclassTextFontExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();//Setting font to the text 
    
      text.setFont(Font.font("verdana",FontWeight.BOLD,FontPosture.REGULAR,20));//setting the position of the text
      text.setX(50); 
      text.setY(130);//Setting the text to be added. 
      text.setText("Hi how are you");//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Setting Font to the text");//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 TextFontExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls TextFontExample
    Output

    On executing, the above program generates a JavaFX window displaying the text with the specified font as follows −

    Setting Font to Text

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

    Stroke and Color of a Text node

    Every node in JavaFX has some default values assigned to it, in regards to the way they are displayed and positioned. For instance, any 3D shape like box, cylinder, sphere etc. has a diffuse color of light gray as its default color.

    You can also change such default values of a JavaFX Text node. A Text node can be designed in various ways: underlined, bold, italic, the text can be written with either double strokes, or wider strokes, etc. All these improvements can be made with the JavaFX Application as well.

    The setFill() Method

    The Text class also inherits the class Shape of the package. Therefore, you can use javafx.scene.shape with which you can set the stroke and color to the text node too.

    You can set the color to the text using the setFill() method of the shape (inherited) class as follows −

    text.setFill(Color.BEIGE);

    Similarly, you can set the stroke color of the text using the method setStroke(). While the width of the stroke can be set using the method setStrokeWidth() as follows −

    //Setting the color 
    text.setFill(Color.BROWN);//Setting the Stroke  
    text.setStrokeWidth(2);//Setting the stroke color 
    text.setStroke(Color.BLUE);

    Example

    The following program is an example that demonstrates how to set the strokeWidth of the text node. In this code, we are setting the stroke width to "2".

    Save this code in a file with the name StrokeExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.paint.Color;importjavafx.scene.text.Font;importjavafx.scene.text.FontPosture;importjavafx.scene.text.FontWeight;importjavafx.scene.text.Text;publicclassStrokeExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();//Setting font to the text 
    
      text.setFont(Font.font("verdana",FontWeight.BOLD,FontPosture.REGULAR,50));//setting the position of the text  
      text.setX(50); 
      text.setY(130);//Setting the Stroke  
      text.setStrokeWidth(2);// Setting the stroke color
      text.setStroke(Color.BLUE);//Setting the text to be added. 
      text.setText("Hi how are you");//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Setting font to the text");//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 the text with the specified stroke and color attributes as follows −

    Text Stroke Example

    Example

    Let us try to color the Save this code in a file with the name ColorExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.stage.Stage;importjavafx.scene.text.*;publicclassColorExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text object Text text =newText();//Setting font to the text 
    
      text.setFont(Font.font("Times New Roman",FontWeight.LIGHT,FontPosture.REGULAR,20));//setting the position of the text  
      text.setX(50); 
      text.setY(130);//Setting the color 
      text.setFill(Color.BROWN);//Setting the text to be added. 
      text.setText("Hi how are you");//Creating a Group object  Group root =newGroup(text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Setting font to the text");//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 ColorExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ColorExample
    Output

    On executing, the above program generates a JavaFX window displaying the text with the specified stroke and color attributes as follows −

    Text Stroke Example

    Applying Decorations to a Text node

    You can also apply decorations such as strike through, in which case a line is passed through the text, and underlining a text using the methods of the Text class.

    You can strike through the text using the method setStrikethrough(). This accepts a Boolean value, pass the value true to this method to strike through the text as shown in the following code box −

    //Striking through the text 
    text1.setStrikethrough(true);

    In the same way, you can underline a text by passing the value true to the method setUnderLine() as follows −

    //underlining the text     
    text2.setUnderline(true);

    Example

    The following program is an example demonstrating how to apply strike through decoration to a text. Save this code in a file with the name StrikeThroughExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.*;publicclassStrikeThroughExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text_Example object Text text1 =newText("Welcome to Tutorialspoint");//Setting font to the text 
    
      text1.setFont(Font.font("verdana",FontWeight.BOLD,FontPosture.REGULAR,20));//setting the position of the text 
      text1.setX(50); 
      text1.setY(75);//strike through the text     
      text1.setStrikethrough(true);//Creating a Group object  Group root =newGroup(text1);//Creating a scene objectScene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Strike Through Decoration Example");//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 StrikeThroughExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls StrikeThroughExample

    Output

    On executing, the above program generates a JavaFX window as shown below −

    Decorations Example

    Example

    The following program is an example demonstrating how to apply underline decoration to a text. Save this code in a file with the name UnderlinesExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.text.*;publicclassUnderlinesExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating a Text_Example object Text text1 =newText("Welcome to Tutorialspoint");//Setting font to the text 
    
      text1.setFont(Font.font("verdana",FontWeight.BOLD,FontPosture.REGULAR,20));//setting the position of the text 
      text1.setX(50); 
      text1.setY(75);//underlining the text     
      text1.setUnderline(true);//Creating a Group object  Group root =newGroup(text1);//Creating a scene objectScene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Underline Decoration Example");//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 UnderlinesExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls UnderlinesExample

    Output

    On executing, the above program generates a JavaFX window as shown below −

    Decorations Example
  • Radial Gradient Pattern

    Like Linear Gradient Pattern, there are various types of gradient patterns that depict the way they’re flowed. The other types are Radial, Angular, Reflected, Diamond gradient patterns. In this chapter, we will learn about the Radial Gradient Pattern.

    The Radial Gradient Pattern is another type of gradient pattern that starts from a center point and flows in a circular manner up to a radius. Simply put, the radial gradient contains two or more color stops in the form of concentric circles.

    JavaFX also provides this type of color pattern to fill circular type of 2D shapes, like a regular circle or an ellipse etc.

    Applying Radial Gradient Pattern

    To apply a Radial Gradient Pattern to the nodes, instantiate the GradientPattern class and pass its object to the setFill(), setStroke() methods.

    The constructor of this class accepts a few parameters, some of which are −

    • startX, startY − These double properties represent the x and y coordinates of the starting point of the gradient.
    • endX, endY − These double properties represent the x and y coordinates of the ending point of the gradient.
    • cycleMethod − This argument defines how the regions outside the color gradient bounds are defined by the starting and ending points and how they should be filled.
    • proportional − This is a Boolean Variable; on setting this property to true the start and end locations are set to a proportion.
    • Stops − This argument defines the color-stop points along the gradient line.
    //Setting the radial gradient Stop[] stops =newStop[]{newStop(0.0,Color.WHITE),newStop(0.3,Color.RED),newStop(1.0,Color.DARKRED)};RadialGradient radialGradient =newRadialGradient(0,0,300,178,60,false,CycleMethod.NO_CYCLE, stops);

    Example

    Following is an example which demonstrates how to apply a radial gradient pattern to the nodes in JavaFX. Here, we are creating a circle and a text nodes and applying gradient pattern to them.

    Save this code in a file with the name RadialGradientExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.paint.CycleMethod;importjavafx.scene.paint.RadialGradient;importjavafx.scene.paint.Stop;importjavafx.stage.Stage;importjavafx.scene.shape.Circle;importjavafx.scene.text.Font;importjavafx.scene.text.Text;publicclassRadialGradientExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a Circle Circle circle =newCircle();//Setting the properties of the circle 
    
      circle.setCenterX(300.0f); 
      circle.setCenterY(180.0f); 
      circle.setRadius(90.0f);//Drawing a text Text text =newText("This is a colored circle");//Setting the font of the text 
      text.setFont(Font.font("Edwardian Script ITC",50));//Setting the position of the text 
      text.setX(155); 
      text.setY(50);//Setting the radial gradient Stop&#91;] stops =newStop&#91;]{newStop(0.0,Color.WHITE),newStop(0.3,Color.RED),newStop(1.0,Color.DARKRED)};RadialGradient radialGradient =newRadialGradient(0,0,300,178,60,false,CycleMethod.NO_CYCLE, stops);//Setting the radial gradient to the circle and text 
      circle.setFill(radialGradient); 
      text.setFill(radialGradient);//Creating a Group object  Group root =newGroup(circle, text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Radial Gradient Example");//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 RadialGradientExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls RadialGradientExample

    Output

    On executing, the above program generates a JavaFX window as follows −

    Radial Gradient

    Example

    Radial Gradient Pattern does not work with shapes that are non-circular; i.e., you can only apply radial gradient on circular and elliptical shapes.

    In the following example, let us try to apply the radial gradient pattern on a Rectangular shape. Save this code in a file with the name RectangleRadialGradient.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.paint.CycleMethod;importjavafx.scene.paint.RadialGradient;importjavafx.scene.paint.Stop;importjavafx.stage.Stage;importjavafx.scene.shape.Rectangle;publicclassRectangleRadialGradientextendsApplication{@Overridepublicvoidstart(Stage stage){Rectangle rct =newRectangle(50.0f,50.0f,200.0f,100.0f);Stop[] stops =newStop[]{newStop(0.0,Color.WHITE),newStop(0.3,Color.RED),newStop(1.0,Color.DARKRED)};RadialGradient radialGradient =newRadialGradient(0,0,300,178,60,false,CycleMethod.NO_CYCLE, stops);  
     
    
      rct.setFill(radialGradient);Group root =newGroup(rct);Scene scene =newScene(root,300,300); 
      stage.setTitle("Radial Gradient Example");   
      stage.setScene(scene);  
      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 RectangleRadialGradient.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls RectangleRadialGradient

    Output

    On executing, you will only see the outermost color of the gradient in the shape as follows −

    Rectangle Radial Gradient
  • Linear Gradient Pattern

    Apart from solid colors, you can also display a color gradient in JavaFX. A color gradient, in color science, is defined as the progression of colors depending on their positions. Hence, a color gradient is also known as color ramp or color progression.

    Traditionally, a color gradient contains colors arranged sequentially or linearly. However, in a linear gradient pattern, the colors are flowing in a single direction. Even if the shape to be coloured is not linear, like a circle or an ellipse, the colors would still be arranged in one direction.

    Let us learn how to apply the linear gradient pattern on 2D shapes in this chapter.

    Applying Linear Gradient Pattern

    To apply a Linear Gradient Pattern to the nodes, instantiate the LinearGradient class and pass its object to the setFill(), setStroke() methods.

    The constructor of this class accepts five parameters namely −

    • startX, startY − These double properties represent the x and y coordinates of the starting point of the gradient.
    • endX, endY − These double properties represent the x and y coordinates of the ending point of the gradient.
    • cycleMethod − This argument defines how the regions outside the color gradient bounds, defined by the starting and ending points, should be filled.
    • proportional − This is a Boolean Variable; on setting this property to true, the start and end locations are set to a proportion.
    • Stops − This argument defines the color-stop points along the gradient line.
    //Setting the linear gradient Stop[] stops =newStop[]{newStop(0,Color.DARKSLATEBLUE),newStop(1,Color.DARKRED)};LinearGradient linearGradient =newLinearGradient(0,0,1,0,true,CycleMethod.NO_CYCLE, stops);

    Example 1

    Following is an example which demonstrates how to apply a gradient pattern to the nodes in JavaFX. Here, we are creating a circle and a text nodes and applying linear gradient pattern to them.

    Save this code in a file with name LinearGradientExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.paint.CycleMethod;importjavafx.scene.paint.LinearGradient;importjavafx.scene.paint.Stop;importjavafx.stage.Stage;importjavafx.scene.shape.Circle;importjavafx.scene.text.Font;importjavafx.scene.text.Text;publicclassLinearGradientExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a Circle Circle circle =newCircle();//Setting the properties of the circle 
    
      circle.setCenterX(300.0f);  
      circle.setCenterY(180.0f); 
      circle.setRadius(90.0f);//Drawing a text Text text =newText("This is a colored circle");//Setting the font of the text 
      text.setFont(Font.font("Edwardian Script ITC",55));//Setting the position of the text 
      text.setX(140); 
      text.setY(50);//Setting the linear gradient Stop&#91;] stops =newStop&#91;]{newStop(0,Color.DARKSLATEBLUE),newStop(1,Color.DARKRED)};LinearGradient linearGradient =newLinearGradient(0,0,1,0,true,CycleMethod.NO_CYCLE, stops);//Setting the linear gradient to the circle and text 
      circle.setFill(linearGradient); 
      text.setFill(linearGradient);//Creating a Group object  Group root =newGroup(circle, text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Linear Gradient Example");//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 LinearGradientExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls LinearGradientExample

    Output

    On executing, the above program generates a JavaFX window as follows −

    Linear Gradient

    Example 2

    Apart from circle, you can also apply this type of gradient on other closed shapes like Polygons. Here, we are creating a triangle and coloring it with a certain linear gradient pattern.

    Save this code in a file with name TriangleLinearGradient.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.scene.paint.CycleMethod;importjavafx.scene.paint.LinearGradient;importjavafx.scene.paint.Stop;importjavafx.stage.Stage;importjavafx.scene.shape.Polygon;publicclassTriangleLinearGradientextendsApplication{@Overridepublicvoidstart(Stage stage){Polygon triangle =newPolygon(); 
    	  
    
      triangle.getPoints().addAll(newDouble&#91;]{100.0,50.0,170.0,150.0,100.0,250.0,});Stop&#91;] stops =newStop&#91;]{newStop(0,Color.ORANGE),newStop(1,Color.YELLOW)};LinearGradient linearGradient =newLinearGradient(0,0,1,0,true,CycleMethod.NO_CYCLE, stops); 
       
      triangle.setFill(linearGradient);Group root =newGroup(triangle);Scene scene =newScene(root,300,300);  
      
      stage.setTitle("Linear Gradient Example"); 
          
      stage.setScene(scene); 
          
      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 TriangleLinearGradient.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls TriangleLinearGradient

    Output

    On executing, the above program generates a JavaFX window as follows −

    Triangle Linear Gradient
  • Colors

    When you draw a 2D shape in a JavaFX application, you might have observed that, by default, it is colored black. But, the color black is not always suitable for all types of applications a user creates. Hence, JavaFX allows you to change this default color into whichever color the user deems perfect for their application.

    To apply colors to an application, JavaFX provides various classes in the package javafx.scene.paint package. This package contains an abstract class named Paint and it is the base class of all the classes that are used to apply colors.

    Using these classes, you can apply colors in the following patterns −

    • Uniform − In this pattern, color is applied uniformly throughout node.
    • Image Pattern − This lets you to fill the region of the node with an image pattern.
    • Gradient − In this pattern, the color applied to the node varies from one point to the other. It has two kinds of gradients namely Linear Gradient and Radial Gradient.

    All those node classes to which you can apply color such as Shape, Text (including Scene), have methods named setFill() and setStroke(). These will help to set the color values of the nodes and their strokes respectively.

    These methods accept an object of type Paint. Therefore, to create either of these type of images, you need to instantiate these classes and pass the object as a parameter to these methods.

    Applying Color to the Nodes

    To set uniform color pattern to the nodes, you need to pass an object of the class color to the setFill()setStroke() methods as follows −

    //Setting color to the text Color color =newColor.BEIGE 
    text.setFill(color);//Setting color to the stroke Color color =newColor.DARKSLATEBLUE 
    circle.setStroke(color);

    In the above code block, we are using the static variables of the color class to create a color object.

    In the same way, you can also use the RGB values or HSB standard of coloring or web hash codes of colors as shown below −

    //creating color object by passing RGB values Color c =Color.rgb(0,0,255);//creating color object by passing HSB valuesColor c =Color.hsb(270,1.0,1.0);//creating color object by passing the hash code for web Color c =Color.web("0x0000FF",1.0);

    Example

    Following is an example which demonstrates, how to apply color to the nodes in JavaFX. Here, we are creating a circle and text nodes and applying colors to them.

    Save this code in a file with the name ColorExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.paint.Color;importjavafx.stage.Stage;importjavafx.scene.shape.Circle;importjavafx.scene.text.Font;importjavafx.scene.text.Text;publicclassColorExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a Circle Circle circle =newCircle();//Setting the properties of the circle 
    
      circle.setCenterX(300.0f); 
      circle.setCenterY(180.0f); 
      circle.setRadius(90.0f);//Setting color to the circle 
      circle.setFill(Color.DARKRED);//Setting the stroke width 
      circle.setStrokeWidth(3);//Setting color to the stroke  
      circle.setStroke(Color.DARKSLATEBLUE);//Drawing a text Text text =newText("This is a colored circle");//Setting the font of the text 
      text.setFont(Font.font("Edwardian Script ITC",50));//Setting the position of the text 
      text.setX(155); 
      text.setY(50);//Setting color to the text 
      text.setFill(Color.BEIGE); 
      text.setStrokeWidth(2); 
      text.setStroke(Color.DARKSLATEBLUE);//Creating a Group object  Group root =newGroup(circle, text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Color Example");//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 ColorExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ColorExample

    Output

    On executing, the above program generates a JavaFX window as follows −

    Color Example

    Applying Image Pattern to the Nodes

    To apply an image pattern to the nodes, instantiate the ImagePattern class and pass its object to the setFill()setStroke() methods.

    The constructor of this class accepts six parameters namely −

    • Image − The object of the image using which you want to create the pattern.
    • x and y − Double variables representing the (x, y) coordinates of origin of the anchor rectangle.
    • height and width − Double variables representing the height and width of the image that is used to create a pattern.
    • isProportional − This is a Boolean Variable; on setting this property to true, the start and end locations are set to be proportional.
    ImagePattern radialGradient =newImagePattern(dots,20,20,40,40,false);

    Example

    Following is an example which demonstrates how to apply image pattern to the nodes in JavaFX. Here, we are creating a circle and a text node and applying an image pattern to them.

    Save this code in a file with name ImagePatternExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.scene.image.Image;importjavafx.scene.paint.Color;importjavafx.scene.paint.ImagePattern;importjavafx.scene.paint.Stop;importjavafx.stage.Stage;importjavafx.scene.shape.Circle;importjavafx.scene.text.Font;importjavafx.scene.text.Text;publicclassImagePatternExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Drawing a Circle Circle circle =newCircle();//Setting the properties of the circle 
    
      circle.setCenterX(300.0f); 
      circle.setCenterY(180.0f); 
      circle.setRadius(90.0f);//Drawing a text Text text =newText("This is a colored circle");//Setting the font of the text 
      text.setFont(Font.font("Edwardian Script ITC",50));//Setting the position of the text
      text.setX(155); 
      text.setY(50);//Setting the image pattern String link ="https://encrypted-tbn1.gstatic.com"+"/images?q=tbn:ANd9GcRQub4GvEezKMsiIf67U"+"rOxSzQuQ9zl5ysnjRn87VOC8tAdgmAJjcwZ2qM";Image image =newImage(link);ImagePattern radialGradient =newImagePattern(image,20,20,40,40,false);//Setting the linear gradient to the circle and text 
      circle.setFill(radialGradient); 
      text.setFill(radialGradient);//Creating a Group object  Group root =newGroup(circle, text);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Image pattern Example");//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 ImagePatternExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls ImagePatternExample

    Output

    On executing, the above program generates a JavaFX window as follows −

    Image Pattern Example
  • ArcTo Path Object

    The Path Element Arc is used to draw an arc to a point in the specified coordinates from the current position.

    It is represented by a class named ArcTo. This class belongs to the package javafx.scene.shape.

    This class has 4 properties of the double datatype namely −

    • X − The x coordinate of the center of the arc.
    • Y − 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.

    To draw the Path element arc, you need to pass values to these properties This can be done 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 PathElement Arc

    To draw an arc to a specified point from the current position in JavaFX, follow the steps given below.

    Step 1: Creating a Path Object

    Create a Path object by instantiating the Path class inside the start() method of Application class as shown below.

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating a Path object Path path =newPath();}}

    Step 2: Create a Path

    Create the MoveTo path element and set the XY coordinates to the starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below.

    //Moving to the starting point MoveTo moveTo =newMoveTo(); 
    moveTo.setX(100.0f); 
    moveTo.setY(150.0f);

    Step 3: Creating an Object of the Class ArcTo

    Create the path element quadratic curve by instantiating the class named ArcTo, which belongs to the package javafx.scene.shape as shown below −

    //Creating an object of the class ArcTo  ArcTo arcTo =newArcTo()

    Step 4: Setting Properties to the Arc Element

    Specify the x, y coordinates of the center of the ellipse (of which this arc is a part of). Then you can specify the radiusX, radiusY, start angle, and length of the arc using their respective setter methods as shown below.

    //setting properties of the path element arc  
    arcTo.setX(300.0); 
    arcTo.setY(50.0); 
    
       
    arcTo.setRadiusX(50.0); arcTo.setRadiusY(50.0);

    Step 5: Adding Elements to the Observable List of Path Class

    Add the path elements MoveTo and arcTo, created in the previous steps to the observable list of the Path class as follows −

    //Adding the path elements to Observable list of the Path class   
    path.getElements().add(moveTo); 
    path.getElements().add(cubicCurveTo);

    Step 6: Launching Application

    Once the Arc path 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 that draws an arc from the current point to a specified position using the class Path of JavaFX. 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.ArcTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassArcExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the class Path  Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(250.0); 
      moveTo.setY(250.0);//Instantiating the arcTo class ArcTo arcTo =newArcTo();//setting properties of the path element arc  
      arcTo.setX(300.0); 
      arcTo.setY(50.0); 
       
      arcTo.setRadiusX(50.0); 
      arcTo.setRadiusY(50.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(arcTo);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage
      stage.setTitle("Drawing an arc through a path");//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, which is drawn from the current position to the specified point, as shown below.

    Drawing Arc Path

    Example

    Let us try to draw an ArcTo Path in JavaFX to create a pendulum object with a circular pendulum moving to and fro on an Arc Path. Save this code in a file with the name ArcToAnimation.java.

    importjavafx.application.Application;importjavafx.animation.PathTransition;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.*;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;importjavafx.util.Duration;publicclassArcToAnimationextendsApplication{@Overridepublicvoidstart(Stage stage){// Drawing a circleCircle circle =newCircle(300.0f,50.0f,40.0f);//Creating an object of the class Path  Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(250.0); 
      moveTo.setY(250.0);//Instantiating the arcTo class ArcTo arcTo =newArcTo();//setting properties of the path element arc  
      arcTo.setX(300.0); 
      arcTo.setY(50.0); 
       
      arcTo.setRadiusX(50.0); 
      arcTo.setRadiusY(50.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(arcTo);//Creating a path transition PathTransition pathTransition =newPathTransition();//Setting the duration of the path transition 
      pathTransition.setDuration(Duration.millis(1000));//Setting the node 
      pathTransition.setNode(circle);//Setting the path 
      pathTransition.setPath(path);//Setting the orientation of the path 
      pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);//Setting the cycle count for the transition 
      pathTransition.setCycleCount(50);//Setting auto reverse value to true 
      pathTransition.setAutoReverse(true);//Playing the animation 
      pathTransition.play();//Creating a Group object  Group root =newGroup();
      root.getChildren().addAll(circle, path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage
      stage.setTitle("Drawing an arc through a path");//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 a pendulum path as shown below.

    Drawing Pendulum
  • CubicCurveTo Path Object

    A Cubic curve is a two dimensional structure that is a type of a Bezier curve. A Bezier curve is defined as a curve that passes through a set of control points (P0…Pn). It is called a Cubic curve when the number of control points are 4 (or, if the order of the curve is 3).

    JavaFX also provides a CubicCurve Path object to draw a more complex shape. Here, we will be considering only the end points of the Cubic Curve and the control points in order to construct a Path object. Let us see how to construct it in detail further.

    CubicCurve Path Object

    The path element cubic curve is used to draw a cubic curve to a point in the specified coordinates from the current position.

    It is represented by a class named CubicCurveTo. This class belongs to the package javafx.scene.shape.

    This class has 6 properties of the double datatype namely −

    • setX − The x coordinate of the point to which a curve is to be drawn from the current position.
    • setX − The y coordinate of the point to which a curve is to be drawn from the current position.
    • controlX1 − The x coordinate of the 1st control point of the curve.
    • controlY1 − The y coordinate of the 1st control point of the curve.
    • controlX2 − The x coordinate of the 2nd control point of the curve.
    • controlY2 − The y coordinate of the 2nd control point of the curve.

    To draw a cubic curve, you need to pass values to these properties. This can be done by passing them to the constructor of this class. These should be in the same order as they were at the time of instantiation; Or, by using their respective setter methods.

    Steps to draw PathElement Cubic Curve

    To draw a cubic curve to a specified point from the current position in JavaFX, follow the steps given below.

    Step 1: Creating a Class

    Create a Cubic Curve Path object inside the start() method of the Application class as shown below.

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating a Path object Path path =newPath();}}

    Step 2: Create a Path

    Create the MoveTo path element and set the XY coordinates to the starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below.

    //Moving to the starting point MoveTo moveTo =newMoveTo(); 
    moveTo.setX(100.0f); 
    moveTo.setY(150.0f);

    Step 3: Creating an Object of the Class CubicCurveTo

    Create the path element quadratic curve by instantiating the class named CubicCurveTo, which belongs to the package javafx.scene.shape as shown below −

    //Creating an object of the class CubicCurveTo CubicCurveTo cubicCurveTo=newCubicCurveTo();

    Step 4: Setting Properties to the Cubic Curve Element

    Specify the coordinates of the point to which a cubic curve is to be drawn from the current position. Then you should set the properties x, y, controlX1, controlY1, controlX2, controlY2 and the coordinates of the control point by their setter methods as shown below.

    //Setting properties of the class CubicCurve            
    cubicCurveTo.setControlX1(400.0f); 
    cubicCurveTo.setControlY1(40.0f); 
    cubicCurveTo.setControlX2(175.0f); 
    cubicCurveTo.setControlY2(250.0f);
    cubicCurveTo.setX(500.0f); 
    cubicCurveTo.setY(150.0f);

    Step 5: Adding Elements to the Observable List of Path Class

    Add the path elements → MoveTo and CubicCurveTo, created in the previous steps to the observable list of the Path class as follows −

    //Adding the path elements to Observable list of the Path class   
    path.getElements().add(moveTo); 
    path.getElements().add(cubicCurveTo);

    Step 6: Launching Application

    Once the CubicCurveTo path 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 the program which draws a cubic curve from the current point to a specified position using the class named Path of JavaFX. Save this code in a file with the name CubicCurveToExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.CubicCurveTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassCubicCurveToExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the class named Path Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the class CubicCurve CubicCurveTo cubicCurveTo =newCubicCurveTo();//Setting properties of the class CubicCurve            
      cubicCurveTo.setControlX1(400.0f); 
      cubicCurveTo.setControlY1(40.0f); 
      cubicCurveTo.setControlX2(175.0f); 
      cubicCurveTo.setControlY2(250.0f); 
      cubicCurveTo.setX(500.0f); 
      cubicCurveTo.setY(150.0f);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo);       
      path.getElements().add(cubicCurveTo);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a cubic through a specified path");//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 CubicCurveToExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveToExample

    Output

    On executing, the above program generates a JavaFX window displaying a Cubic curve. This is drawn from the current position to the specified point as shown below.

    Drawing Cubic Curve Path

    Example

    In another example, we are trying to apply Stroke Transition Animation on Cubic Curve Path. Here, the stroke of said 2D shape is set to change its color from BLACK to BROWN. Save this code in a file with the name CubicCurveToAnimation.java.

    importjavafx.application.Application;importjavafx.animation.StrokeTransition;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.CubicCurveTo;importjavafx.util.Duration;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;importjavafx.scene.paint.Color;publicclassCubicCurveToAnimationextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the class named Path Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the class CubicCurve CubicCurveTo cubicCurveTo =newCubicCurveTo();//Setting properties of the class CubicCurve            
      cubicCurveTo.setControlX1(400.0f); 
      cubicCurveTo.setControlY1(40.0f); 
      cubicCurveTo.setControlX2(175.0f); 
      cubicCurveTo.setControlY2(250.0f); 
      cubicCurveTo.setX(500.0f); 
      cubicCurveTo.setY(150.0f);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo);       
      path.getElements().add(cubicCurveTo);//creating stroke transition  StrokeTransition st =newStrokeTransition();//Setting the duration of the transition 
      st.setDuration(Duration.millis(1000));//Setting the shape for the transition 
      st.setShape(path);//Setting the fromValue property of the transition (color) 
      st.setFromValue(Color.BLACK);//Setting the toValue property of the transition (color) 
      st.setToValue(Color.BROWN);//Setting the cycle count for the transition 
      st.setCycleCount(50);//Setting auto reverse value to false 
      st.setAutoReverse(false);//Playing the animation 
      st.play();//Creating a Group object  Group root =newGroup(path);//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 CubicCurveToAnimation.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls CubicCurveToAnimation

    Output

    On executing, the above program generates a JavaFX window displaying a Cubic curve with the Stroke transition. This is drawn from the current position to the specified point as shown below.

    Drawing Cubic Curve Path
  • QuadCurveTo Path Object

    Quadratic Curve or QuadCurve is generally defined as the curve that is defined by a quadratic equation. In JavaFX, we make use of 6 different properties to create this QuadCurve node. And to create a complex shape using QuadCurve, we would have to specify these properties everytime it is required.

    JavaFX makes this process simpler by providing a QuadCurve path object that takes lesser number of properties to draw it.

    We will learn about the QuadCurve Path object in detail further in this chapter.

    QuadCurve Path Object

    The path element quadratic curve is used to draw a quadratic curve to a point in the specified coordinates from the current position.

    It is represented by a class named QuadraticCurveTo. This class belongs to the package javafx.scene.shape.

    This class has 4 properties of the double datatype namely −

    • setX − The x coordinate of the point to which a curve is to be drawn from the current position.
    • setY − The y coordinate of the point to which a curve is to be drawn from the current position.
    • controlX − The x coordinate of the control point of the curve.
    • controlY − The y coordinate of the control point of the curve.

    To draw a quadratic 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 their respective setter methods.

    Steps to draw PathElement Quadratic Curve

    To draw a quadratic curve to a specified point from the current position in JavaFX, follow the steps given below.

    Step 1: Creating a Path Object

    Instantiate the Path class to create a Path object within the start() method of Application class as shown below −

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating a Path object Path path =newPath();}}

    Step 2: Create a Path

    Create the MoveTo path element and set the XY coordinates to the starting point of the line to the coordinates (100, 150). This can be done by using the methods setX() and setY() of the class MoveTo as shown below.

    //Moving to the starting point MoveTo moveTo =newMoveTo(); 
    moveTo.setX(100.0f); 
    moveTo.setY(150.0f);

    Step 3: Creating an Object of the Class QuadCurveTo

    Create the path element Quadratic Curve by instantiating the class named QuadCurveTo which belongs to the package javafx.scene.shape as follows.

    //Creating an object of the class QuadCurveTo QuadCurveTo quadCurveTo =newQuadCurveTo()

    Step 4: Setting Properties to the Quadratic Curve Element

    Specify the coordinates of the point to which a Quadratic Curve is to be drawn from the current position. Then you should set the properties x, y, controlx, controlY and the coordinates of the control point by their setter methods as shown below.

    //Setting properties of the class QuadCurve            
    quadCurveTo.setX(500.0f); 
    quadCurveTo.setY(220.0f); 
    quadCurveTo.setControlX(250.0f); 
    quadCurveTo.setControlY(0.0f);

    Step 5: Adding Elements to the Observable List of the Path Class

    Add the path elements MoveTo and QuadraticCurveTo created in the previous steps to the observable list of the Path class as follows −

    //Adding the path elements to Observable list of the Path class   
    path.getElements().add(moveTo); 
    path.getElements().add(quadCurveTo)

    Step 6: Launching Application

    Once the QuadCurveTo path 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 1

    Following is a program which draws a quadratic curve from the current point to a specified position using the class named Path of JavaFX. Save this code in a file with the name QuadCurveToExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;importjavafx.scene.shape.QuadCurveTo;publicclassQuadCurveToExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the class named Path Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the class QuadCurve QuadCurveTo quadCurveTo =newQuadCurveTo();//Setting properties of the class QuadCurve            
      quadCurveTo.setX(500.0f); 
      quadCurveTo.setY(220.0f); 
      quadCurveTo.setControlX(250.0f);  
      quadCurveTo.setControlY(0.0f);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(quadCurveTo);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a QuadCurve through a specified path");//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 QuadCurveToExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveToExample

    Output

    On executing, the above program generates a JavaFX window displaying a quadratic curve. This is drawn from the current position to the specified point as shown below.

    Drawing Quadratic Curve

    Example 2

    In this example, let us try to apply some animation to this QuadCurve Path. Here, we are drawing a sample QuadCurve and applying the Fade Transition to it. Save this code in a file with the name QuadCurveToAnimation.java.

    importjavafx.application.Application;importjavafx.animation.FadeTransition;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;importjavafx.scene.shape.QuadCurveTo;importjavafx.util.Duration;publicclassQuadCurveToAnimationextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the class named Path Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the class QuadCurve QuadCurveTo quadCurveTo =newQuadCurveTo();//Setting properties of the class QuadCurve            
      quadCurveTo.setX(500.0f); 
      quadCurveTo.setY(220.0f); 
      quadCurveTo.setControlX(250.0f);  
      quadCurveTo.setControlY(0.0f);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(quadCurveTo);//Creating the fade Transition FadeTransition fadeTransition =newFadeTransition(); 
    fadeTransition.setDuration(Duration.millis(1000));//Setting the node for Transition
      fadeTransition.setNode(path);//Setting the property fromValue of the transition (opacity) 
      fadeTransition.setFromValue(1.0);//Setting the property toValue of the transition (opacity) 
      fadeTransition.setToValue(0.3);//Setting the cycle count for the transition 
      fadeTransition.setCycleCount(50);//Setting auto reverse value to false 
      fadeTransition.setAutoReverse(false);//Playing the animation 
      fadeTransition.play();//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a QuadCurve through a specified path");//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 QuadCurveToAnimation.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls QuadCurveToAnimation

    Output

    On executing, the above program generates a JavaFX window displaying a quadratic curve that is fading out. This is drawn from the current position to the specified point as shown below.

    Drawing Quadratic Curve
  • VLineTo Path Object

    The path element VLineTo is used to draw a vertical line to a point in the specified coordinates from the current position.

    It is represented by a class named VLineTo. This class belongs to the package javafx.scene.shape.

    This class has a property of the double datatype namely −

    • Y − The y coordinate of the point to which a vertical is to be drawn from the current position.

    To draw the path element vertical line, you need to pass a value to this property. This can be done either by passing it to the constructor of this class at the time of instantiation; Or, by using its respective setter methods.

    Steps to draw PathElement Vertical Line

    To draw a vertical line to a specified point from the current position in JavaFX, follow the steps given below.

    Step 1: Creating a Class

    Create a Java class and inherit the Application class of the package javafx.application and implement the start() method of this class. Then create a path object by instantiating the Path class as follows.

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating a Path object Path path =newPath()}}

    Step 2: Create a Path

    Create the MoveTo path element and set XY coordinates to the starting point of the line to the coordinates (100, 150). This can be done by using the methods setX() and setY() of the class MoveTo as shown below.

    //Moving to the starting point MoveTo moveTo =newMoveTo(); 
    moveTo.setX(100.0f); 
    moveTo.setY(150.0f)

    Step 3: Creating an object of the class VLineTo

    Create the path element vertical line by instantiating the class named VLineTo, which belongs to the package javafx.scene.shape as follows.

    //Creating an object of the class VLineTo  VLineTo vLineTo =newVLineTo();

    Step 4:Setting Properties to the Element Vertical Line

    Specify the coordinates of the point to which a vertical line is to be drawn from the current position. This can be done by setting the properties x and y using their respective setter methods as shown in the following code block.

    //Setting the Properties of the vertical line element 
    lineTo.setX(500.0f); 
    lineTo.setY(150.0f);

    Step 5: Adding Elements to the Observable List of the Path Class

    Add the path elements MoveTo and VlineTo created in the previous steps to the observable list of the Path class as follows −

    //Adding the path elements to Observable list of the Path class   
    path.getElements().add(moveTo); 
    path.getElements().add(VlineTo);

    Step 6: Launching Application

    Once the VLineTo path 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 1

    Following is a program which draws a vertical line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name − VLineToExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.VLineTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassVLineToExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the Path class Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the VLineTo class VLineTo vLineTo =newVLineTo();//Setting the properties of the path element vertical line 
      vLineTo.setY(10.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(vLineTo);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a vertical 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 VLineToExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls VLineToExample

    Output

    On executing, the above program generates a JavaFX window displaying a vertical line, which is drawn from the current position to the specified point, as shown below.

    Drawing Vertical Line

    Example 2

    Following is a program which draws a rectangle using both vertical lines and horizontal lines using the class Path of JavaFX. Save this code in a file with the name − VLineToRectangle.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.HLineTo;importjavafx.scene.shape.LineTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassVLineToRectangleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the Path class Path path =newPath();//Drawing a triangular pathMoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(200.0); 
      moveTo.setY(150.0);HLineTo hLineTo =newHLineTo();                
      hLineTo.setX(100.0);MoveTo moveTo2 =newMoveTo(); 
      moveTo2.setX(100.0); 
      moveTo2.setY(150.0);LineTo lineTo =newLineTo();                
      lineTo.setX(150.0);
      lineTo.setY(50.0);MoveTo moveTo3 =newMoveTo(); 
      moveTo3.setX(150.0); 
      moveTo3.setY(50.0);LineTo lineTo2 =newLineTo();       
      lineTo2.setX(200.0);
      lineTo2.setY(150.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(hLineTo);
      path.getElements().add(moveTo2); 
      path.getElements().add(lineTo);
      path.getElements().add(moveTo3); 
      path.getElements().add(lineTo2);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Triangular Path");//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 VLineToRectangle.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls VLineToRectangle

    Output

    On executing, the above program generates a JavaFX window displaying a rectangle.

    VLineTo Rectangle
  • HLineTo Path Object

    The path element HLineTo is used to draw a horizontal line to a point in the specified coordinates from the current position.

    It is represented by a class named HLineTo. This class belongs to the package javafx.scene.shape.

    This class has a property of the double datatype namely −

    • X − The x coordinate of the point to which a horizontal line is to be drawn from the current position.

    To draw a path element horizontal line, you need to pass a value to this property. This can be either done by passing it to the constructor of this class, at the time of instantiation; Or, by using their respective setter methods.

    Steps to draw PathElement Horizontal Line

    Follow the steps given below to draw a horizontal line to a specified point from the current position in JavaFX.

    Step 1: Creating a Path Object

    We first create a Path object by instantiating the Path class within the start() method of Application class as shown below −

    publicclassClassNameextendsApplication{@Overridepublicvoidstart(Stage primaryStage)throwsException{//Creating a Path object Path path =newPath()}}

    Step 2: Setting the Initial Point

    Create the MoveTo path element and set XY coordinates to starting point of the line to the coordinates (100, 150). This can be done by using the methods setX() and setY() of the class MoveTo as shown below.

    //Moving to the starting point  MoveTo moveTo =newMoveTo(); 
    moveTo.setX(100.0f); 
    moveTo.setY(150.0f);

    Step 3: Creating an Object of the Class HLineTo

    Create the path element horizontal line by instantiating the class named HLineTo which belongs to the package javafx.scene.shape as shown below.

    //Creating an object of the class HLineTo  HLineTo hLineTo =newHLineTo();

    Step 4: Setting Properties to the Horizontal Line Element

    Specify the x coordinate of the point to which a horizontal line is to be drawn from the current position. This can be done by setting the property x, using the method setX() of the HLineTo class as shown below.

    //Setting the Properties of the horizontal line element 
    hlineTo.setX(400)

    Step 5: Adding Elements to the Observable List of Path Class

    Add the path elements MoveTo and HlineTo created in the previous steps to the observable list of the Path class as shown below −

    //Adding the path elements to Observable list of the Path class   
    path.getElements().add(moveTo); 
    path.getElements().add(hlineTo);

    Step 6: Launching Application

    Once the HLineTo path 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 draws a horizontal line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name − HLineToExample.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.HLineTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassHLineToExampleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the Path class Path path =newPath();//Moving to the starting point MoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(100.0); 
      moveTo.setY(150.0);//Instantiating the HLineTo class HLineTo hLineTo =newHLineTo();//Setting the properties of the path element horizontal line 
      hLineTo.setX(10.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(hLineTo);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a horizontal 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 HLineToExample.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls HLineToExample

    Output

    On executing, the above program generates a JavaFX window displaying a horizontal line, which is drawn from the current position to the specified point, as shown below.

    Drawing Horizontal Line

    Example

    In this example, we are trying to draw a more complex path, i.e. triangle, using the horizontal line. Save this code in a file with the name − HLineToTriangle.java.

    importjavafx.application.Application;importjavafx.scene.Group;importjavafx.scene.Scene;importjavafx.stage.Stage;importjavafx.scene.shape.HLineTo;importjavafx.scene.shape.LineTo;importjavafx.scene.shape.MoveTo;importjavafx.scene.shape.Path;publicclassHLineToTriangleextendsApplication{@Overridepublicvoidstart(Stage stage){//Creating an object of the Path class Path path =newPath();//Drawing a triangular pathMoveTo moveTo =newMoveTo(); 
    
      moveTo.setX(200.0); 
      moveTo.setY(150.0);HLineTo hLineTo =newHLineTo();                
      hLineTo.setX(100.0);MoveTo moveTo2 =newMoveTo(); 
      moveTo2.setX(100.0); 
      moveTo2.setY(150.0);LineTo lineTo =newLineTo();                
      lineTo.setX(150.0);
      lineTo.setY(50.0);MoveTo moveTo3 =newMoveTo(); 
      moveTo3.setX(150.0); 
      moveTo3.setY(50.0);LineTo lineTo2 =newLineTo();       
      lineTo2.setX(200.0);
      lineTo2.setY(150.0);//Adding the path elements to Observable list of the Path class 
      path.getElements().add(moveTo); 
      path.getElements().add(hLineTo);
      path.getElements().add(moveTo2); 
      path.getElements().add(lineTo);
      path.getElements().add(moveTo3); 
      path.getElements().add(lineTo2);//Creating a Group object  Group root =newGroup(path);//Creating a scene object Scene scene =newScene(root,600,300);//Setting title to the Stage 
      stage.setTitle("Drawing a Triangular Path");//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 HLineToTriangle.java 
    java --module-path %PATH_TO_FX%--add-modules javafx.controls HLineToTriangle

    Output

    On executing, the above program generates a JavaFX window displaying a triangle.

    Drawing Horizontal Line