JavaFX – 2D Shapes ”; Previous Next In the previous chapter, we have seen the basic application of JavaFX, where we learnt how to create an empty window and how to draw a line on an XY plane of JavaFX. In addition to the line, we can also draw several other 2D shapes. 2D Shape In general, a 2D shape is a geometrical figure that can be drawn on the XY plane, these include Line, Rectangle, Circle, etc. Using the JavaFX library, you can draw − Predefined shapes such as Line, Rectangle, Circle, Ellipse, Polygon, Polyline, Cubic Curve, Quad Curve, Arc. Path elements such as MoveTO Path Element, Line, Horizontal Line, Vertical Line, Cubic Curve, Quadratic Curve, Arc. In addition to these, you can also draw a 2D shape by parsing SVG path. Each of the above mentioned 2D shape is represented by a class and all these classes belongs to the package javafx.scene.shape. The class named Shape is the base class of all the 2-Dimensional shapes in JavaFX. Creating a 2D Shape in JavaFX To create a chart, you need to − Instantiate the respective class of the required shape. Set the properties of the shape. Add the shape object to the group. Instantiating the Respective Class To create a 2 Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a circle you need to instantiate the class named Circle as follows − Circle circle = new Circle(); Setting the Properties of the Shape After instantiating the class, you need to set the properties for the shape using the setter methods. For example, you can set the X, Y coordinates of the center of the Circle class and its radius, using the following setter methods − // Setting the Properties of a circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); circle.setRadius(100.0f); Adding the Shape Object to the Group Finally, you need to add the circle object to the group by passing it as a parameter of the constructor as shown below. //Creating a Group object Group root = new Group(circle); Various 2D Shapes available in JavaFX The following table gives you the list of various shapes (classes) provided by JavaFX. S.No Shape & Description 1 Line A line is a geometrical structure joining two point. The Line class of the package javafx.scene.shape represents a line in the XY plane. 2 Rectangle In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles. In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape. 3 Rounded Rectangle In JavaFX, you can draw a rectangle either with sharp edges or with arched edges and The one with arched edges is known as a rounded rectangle. 4 Circle A circle is a line forming a closed loop, every point on which is a fixed distance from a centre point. In JavaFX, a circle is represented by a class named Circle. This class belongs to the package javafx.scene.shape. 5 Ellipse An ellipse is defined by two points, each called a focus. If any point on the ellipse is taken, the sum of the distances to the focus points is constant. The size of the ellipse is determined by the sum of these two distances. In JavaFX, an ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape. 6 Polygon A closed shape formed by a number of coplanar line segments connected end to end. In JavaFX, a polygon is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. 7 Polyline A polyline is same a polygon except that a polyline is not closed in the end. Or, continuous line composed of one or more line segments. In JavaFX, a Polyline is represented by a class named Polygon. This class belongs to the package javafx.scene.shape. 8 Cubic Curve A cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape. 9 QuadCurve A quadratic curve is a Bezier parametric curve in the XY plane is a curve of degree 2. In JavaFX, a QuadCurve is represented by a class named QuadCurve. This class belongs to the package javafx.scene.shape. 10 Arc An arc is part of a curve. In JavaFX, an arc is represented by a class named Arc. This class belongs to the package − javafx.scene.shape. Types Of Arc In addition to this we can draw three types of arc”s Open, Chord, Round. 11 SVGPath 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. This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn.. Properties of 2D Objects For all the 2-Dimensional objects, you can set various properties like fill, stroke, StrokeType, etc. The following section discusses various properties of 2D objects. Stroke Type Property Stroke Width Property Stroke Fill Property Stroke Property Stroke Line Property Stroke Miter Limit Property Stroke Line Cap Property Smooth Property We will learn about these properties in detail, in further sections of this tutorial. Operations on 2D Objects If we add more than one shape to a group, the first shape is overlapped by the second one as shown below. In addition to the transformations (rotate, scale, translate, etc.), transitions (animations), you can also perform three operations on 2D objects namely − Union, Subtraction and Intersection. Union Operation: This operation takes two or more shapes as inputs and returns the area occupied by them. Intersection Operation: This operation takes two or more shapes as inputs and returns the intersection area between them. Subtraction Operation: This operation takes two or more shapes as an input.
Category: javafx
JavaFX – Drawing a Line
JavaFX – Drawing a Line ”; Previous Next Generally, a line is a geometrical structure which is infinitely long on a multi-dimensional plane (Say, an XY plane). This geometrical figure does not have any start and end points; neither does it have measurable dimensions like width, depth etc. Even though a line is a one-dimensional object, it can still exist in two or higher dimensional planes. However, a segment of this line with both start and end points, called the “line segment” is used in everyday geometry; which is also the figure that we learn how to create using JavaFX, in this chapter. It is drawn as shown in the image below. Line in JavaFX In JavaFX, a line, or a line segment, is represented by a class named Line. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a line node in JavaFX. This class has 4 properties of the double datatype namely − startX − The x coordinate of the start point of the line. startY − The y coordinate of the start point of the line. endX − The x coordinate of the end point of the line. endY − The y coordinate of the end point of the line. To draw a line, 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. Steps to Draw a Line in JavaFX Follow the steps given below to Draw a Line in JavaFX. Step 1: Creating a Line You can create a line in JavaFX by instantiating the class named Line which belongs to a package javafx.scene.shape. Instantiate this class as shown below − //Creating a line object Line line = new Line(); Note that the entire code to implement JavaFX graphics, which includes the instantiation of Line class, must be written within the start() method of Application class, as shown below − public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { // Write code here Line line = new Line(); } } Step 2: Setting Properties to the Line Specify the coordinates to draw the line on an XY plane by setting the properties startX, startY, endX and endY, using their respective setter methods as shown in the following code block. line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); Step 3: Adding Line Object to Group Instantiate the Group class of package javafx.scene, by passing the Line object as a parameter value to its constructor as follows − Group root = new Group(line); 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 the program which generates a straight line using JavaFX. Save this code in a file with the name DrawingLine.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Line; import javafx.stage.Stage; public class DrawingLine extends Application{ @Override public void start(Stage stage) { //Creating a line object Line line = new Line(); //Setting the properties to a line line.setStartX(100.0); line.setStartY(150.0); line.setEndX(500.0); line.setEndY(150.0); //Creating a Group Group root = new Group(line); //Creating a Scene Scene scene = new Scene(root, 600, 300); //Setting title to the scene stage.setTitle(“Sample application”); //Adding the scene to the stage stage.setScene(scene); //Displaying the contents of a scene stage.show(); } public static void main(String args[]){ launch(args); } } 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 DrawingLine.java java –module-path %PATH_TO_FX% –add-modules javafx.controls DrawingLine Output On executing, the above program generates a JavaFX window displaying a straight line as shown below. Drawing Multiple Lines You can also draw multiple lines on a single application by grouping all the lines together using addAll() function. An example demonstrating the same is as follows. In here, we are drawing a square using four lines and coloring the background “pink”. Save this code in a file with the name DrawingMultipleLines.java. Example import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Line; import javafx.stage.Stage; public class DrawingMultipleLines extends Application{ @Override public void start(Stage stage) { //Creating a line object Line line1 = new Line(); //Setting the properties to a line line1.setStartX(100.0); line1.setStartY(150.0); line1.setEndX(200.0); line1.setEndY(150.0); // Setting Properties to other lines // without setter methods Line line2 = new Line(200, 150, 200, 250); Line line3 = new Line(200, 250, 100, 250); Line line4 = new Line(100, 250, 100, 150); //Creating a Group Group root = new Group(); root.getChildren().addAll(line1,line2,line3,line4); //Creating a Scene Scene scene = new Scene(root, 400, 400, Color.PINK); //Setting title to the scene stage.setTitle(“Sample application”); //Adding the scene to the stage stage.setScene(scene); //Displaying the contents of a scene stage.show(); } public static void main(String args[]){ launch(args); } } 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 DrawingMultipleLines.java java –module-path %PATH_TO_FX% –add-modules javafx.controls DrawingMultipleLines Output The output window of the program above will be obtained as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Creating a Box
JavaFX – Creating a Box ”; Previous Next A cuboid is a three-dimensional solid shape. Cuboids are composed of 6 rectangles, which are placed at right angles. A cuboid that uses square faces is a cube, if the faces are rectangles, other than cubes, it looks like a shoe box. A cuboid is a three-dimensional shape with a length (depth), width, and a height as shown in the following diagram − In JavaFX, this type of three-dimensional shape is addressed as a Box; as it can either be a cuboid or cube, depending on the measurements of the shape. Box in JavaFX In JavaFX, a 3-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Box node in JavaFX. This class has 3 properties of the double datatype, which are − width − The width of the box. height − The height of the box. depth − The depth of the box. To draw a cubic curve, you need to pass values to these properties by passing them to the constructor of this class. This has to be done in the same order at the time of instantiation; or, by using their respective setter methods. Steps to Draw 3D Box To Draw a 3D box in JavaFX, follow the steps given below. Step 1: Creating a Box You can create a Box in JavaFX by instantiating the class named BOX, which belongs to a package javafx.scene.shape. You can instantiate this class within the start() method of the Application class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating an object of the class Box Box box = new Box(); } } Step 2: Setting Properties to the Box Set the properties of the 3D box, Width, Height and Depth, using their respective setter methods as shown in the following code block. //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); Step 3: Creating a Group Object In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the Box (node) object, created in the previous step, as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows − Group root = new Group(box); Step 4: Launching an Application Once the 3D object is created, launch the JavaFX application by following the steps below − Instantiate the class named Scene by passing the Group object as a parameter value to its constructor. You can also pass dimensions of the application screen as optional parameters to the constructor. Set the title to the stage using the setTitle() method of the Stage class. Add a scene object 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 within the Application class. Example Following is a program which generates a 3D box using JavaFX. Save this code in a file with the name BoxExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.stage.Stage; public class BoxExample extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box = new Box(); //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); //Creating a Group object Group root = new Group(box); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Box”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 BoxExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls BoxExample Output On executing, the above program generates a JavaFX window displaying a 3D Box as shown below − Example In the previous example, we did not specify the start and end coordinates to draw the box from. However, using translateX and translateY properties of animation class, we can relocate the box on the JavaFX application. Let us look at an example below and save it in a file named TranslateBoxExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.scene.paint.Color; import javafx.scene.transform.Translate; import javafx.stage.Stage; public class TranslateBoxExample extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box = new Box(); //Setting the properties of the Box box.setWidth(200.0); box.setHeight(200.0); box.setDepth(200.0); Translate translate = new Translate(); translate.setX(200); translate.setY(150); translate.setZ(25); box.getTransforms().addAll(translate); //Creating a Group object Group root = new Group(box); //Creating a scene object Scene scene = new Scene(root, 400, 300); scene.setFill(Color.web(“#81c483”)); //Setting title to the Stage stage.setTitle(“Translate a Box”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 TranslateBoxExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls TranslateBoxExample Output On executing, the above program generates a JavaFX window displaying a 3D Box as shown below. We coloured the scene in order to differentiate the translated location of the box. Print Page Previous Next Advertisements ”;
JavaFX – Fade Transition
JavaFX – Fade Transition ”; Previous Next A Fade transition is a type of a geometrical transition that changes the opacity property of an object. Using fade transition, you can either reduce the opacity of the object or increase it. This transition is known as a geometrical transition as it deals with the geometry of an object. In JavaFX, the fade transition is used to transition a node”s opacity from a starting value to an ending value over a specified duration. This can be done using the FadeTransition class belonging to the javafx.animation package. Fade Transition in JavaFX You can apply the fade transition to a JavaFX object using the FadeTransition class properties. You have to set the starting value and ending value of the transition using fromValue and toValue. When fromValue is not specified, the node”s current opacity value is considered by default; and when toValue is not specified, the byValue is added to the starting value. Note that Transition properties − fromValue, toValue and byValue, cannot be changed while a transition is running. However, if you attempt to change a property while the transition is running, the change is ignored. Hence, the animation must be stopped and restarted to assign the new property value(s) to the transition. No exception is thrown either. The FadeTransition class contains the following properties − byValue − Specifies the incremented stop opacity value, from the start, of this FadeTransition. duration − The duration of this FadeTransition. fromValue − Specifies the start opacity value for this FadeTransition. node − The target node of this Transition. toValue − Specifies the stop opacity value for this FadeTransition. Example Following is the program which demonstrates Fade Transition in JavaFX. Save this code in a file with the name FadeTransitionExample.java. import javafx.animation.FadeTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class FadeTransitionExample extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the position of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); //Setting the radius of the circle circle.setRadius(100.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Creating the fade Transition FadeTransition fadeTransition = new FadeTransition(Duration.millis(1000)); //Setting the node for Transition fadeTransition.setNode(circle); //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 = new Group(circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Fade transition example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 FadeTransitionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls FadeTransitionExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Drawing a Polyline
JavaFX – Drawing a Polyline ”; Previous Next 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 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 = new Polyline(doubleArray); Or, by using the getPoints() method as follows − polyline.getPoints().addAll(new Double[]{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. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating an object of the class Polyline Polyline polyline = new Polyline(); } } 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(new Double[]{ 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 = new Group(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. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Polyline public class PolylineExample1 extends Application { @Override public void start(Stage stage) { //Creating a polyline Polyline polyline = new Polyline(); //Adding coordinates to the polygon polyline.getPoints().addAll(new Double[]{ 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 = new Group(polyline); //Creating a scene object Scene scene = new Scene(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(); } public static void main(String args[]){ launch(args); } } 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. Example In this example, let us try to draw a polyline of 4 vertices. You can save the file name as PolylineExample2.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polyline; import javafx.stage.Stage; public class PolylineExample2 extends Application { @Override public void start(Stage stage) { //Creating a Polyline Polyline polyline = new Polyline(); //Adding coordinates to the polygon polyline.getPoints().addAll(new Double[]{ 300.0, 50.0, 450.0, 150.0, 300.0, 250.0, 150.0, 150.0, }); //Creating a Group object Group root = new Group(polyline); //Creating a scene object Scene scene = new Scene(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(); } public static void main(String args[]){ launch(args); } } 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. Print Page Previous Next Advertisements ”;
JavaFX – Path Transition
JavaFX – Path Transition ”; Previous Next A path transition in JavaFX is used to move a JavaFX node (or object) around a specific path. This is similar to translate transition, as it also moves the object from one position to another. However, the translate transition does not provide a continuous path through which the object moves; which path transition does. Any JavaFX node, like a 2D or 3D shape, text, image etc., can be moved along any path: straight or curved. Path Transition in JavaFX JavaFX offers a PathTransition class to apply the path transition on a JavaFX node. This class belongs to the javafx.animation package. This Transition creates a path animation that moves an object in a certain path and spans its duration. Path transition does nothing but translate an object in order to relocate it. This translation along a path is done by updating the coordinates of the node in both X and Y directions, and by updating the orientation to OrientationType.ORTHOGONAL_TO_TANGENT, at regular interval. The animated path is defined by the outline of any JavaFX shape. The PathTransition class offers the following properties to be applied on a node − duration − The duration of this Transition. node − The target node of this PathTransition. orientation − Specifies the upright orientation of node along the path. path − The shape on which outline the node should be animated. Example 1 Following is the program which demonstrates Path Transition in JavaFX. Save this code in a file with the name PathTransitionExample.java. import javafx.animation.PathTransition; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; import javafx.util.Duration; public class PathTransitionExample extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the position of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); //Setting the radius of the circle circle.setRadius(25.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Instantiating the path class Path path = new Path(); //Creating the MoveTo path element MoveTo moveTo = new MoveTo(100, 150); //Creating the Cubic curve path element CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(cubicCurveTo); //Creating a path transition PathTransition pathTransition = new PathTransition(); //Setting the duration of the path transition pathTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition pathTransition.setNode(circle); //Setting the path pathTransition.setPath(path); //Setting the orientation of the path pathTransition.setOrientation(PathTransition.OrientationType. ORTHOGONAL_TO_TAN GENT); //Setting the cycle count for the transition pathTransition.setCycleCount(50); //Setting auto reverse value to false pathTransition.setAutoReverse(false); //Playing the animation pathTransition.play(); //Creating a Group object Group root = new Group(circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Path transition example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 PathTransitionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls PathTransitionExample Output On executing, the above program generates a JavaFX window as shown below. Example 2 Following is an example which transforms a circle along a complex path. Save this code in a file with name PathTransitionExample2.java. import javafx.animation.PathTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; import javafx.util.Duration; public class PathTransitionExample2 extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the position of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); //Setting the radius of the circle circle.setRadius(25.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Creating a Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(108, 71); //Creating 1st line LineTo line1 = new LineTo(321, 161); //Creating 2nd line LineTo line2 = new LineTo(126,232); //Creating 3rd line LineTo line3 = new LineTo(232,52); //Creating 4th line LineTo line4 = new LineTo(269, 250); //Creating 5th line LineTo line5 = new LineTo(108, 71); //Adding all the elements to the path path.getElements().add(moveTo); path.getElements().addAll(line1, line2, line3, line4, line5); //Creating the path transition PathTransition pathTransition = new PathTransition(); //Setting the duration of the transition pathTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition pathTransition.setNode(circle); //Setting the path for the transition pathTransition.setPath(path); //Setting the orientation of the path pathTransition.setOrientation( PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT); //Setting the cycle count for the transition pathTransition.setCycleCount(50); //Setting auto reverse value to true pathTransition.setAutoReverse(false); //Playing the animation pathTransition.play(); //Creating a Group object Group root = new Group(circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Path transition example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 PathTransitionExample2.java java –module-path %PATH_TO_FX% –add-modules javafx.controls PathTransitionExample2 Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Drawing a Quad Curve ”; Previous Next 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 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. public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { //Creating an object of the class QuadCurve QuadCurve quadcurve = new QuadCurve(); } } 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 = new QuadCurve(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 = new Group(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. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.QuadCurve; public class QuadCurveExample extends Application { @Override public void start(Stage stage) { //Creating a QuadCurve QuadCurve quadCurve = new QuadCurve(); //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 = new Group(quadCurve); //Creating a scene object Scene scene = new Scene(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(); } public static void main(String args[]){ launch(args); } } 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. 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. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.Bloom; import javafx.stage.Stage; import javafx.scene.paint.Color; import javafx.scene.shape.QuadCurve; public class QuadCurveEffect extends Application { @Override public void start(Stage stage) { //Creating a QuadCurve QuadCurve quadCurve = new QuadCurve(); //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 = new Bloom(); //setting threshold for bloom bloom.setThreshold(0.1); //Applying bloom effect to quadCurve quadCurve.setEffect(bloom); //Creating a Group object Group root = new Group(quadCurve); //Creating a scene object Scene scene = new Scene(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(); } public static void main(String args[]){ launch(args); } } 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. Print Page Previous Next Advertisements ”;
JavaFX – Translation Transformation ”; Previous Next A translation transformation simply moves an object to a different position on the same plane. You can translate a point in a 2D plane by adding translation coordinate (tx, ty) to the original coordinate (X, Y); this will get you the new coordinate (X’, Y’) where the point is relocated to. Translation Transformation in JavaFX In JavaFX, using the Translation transformation, a node can be shifted from one position to another position in the same application. This transformation is applied on a JavaFX node with the help of Translate class in javafx.scene.transform package. This class represents an Affine object that relocates the coordinates within the JavaFX application. Example 1 Following is the program which demonstrates translation in JavaFX. Here, we are creating 2 circles (nodes) at the same location with the same dimensions, but with different colors (Brown and Cadetblue). We are also applying translation on the circle with a cadetblue color. Save this code in a file with the name TranslationExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.transform.Translate; import javafx.stage.Stage; public class TranslationExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle = new Circle(); //Setting the position of the circle circle.setCenterX(150.0f); circle.setCenterY(135.0f); //Setting the radius of the circle circle.setRadius(100.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(150.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.CADETBLUE); //Setting the stroke width of the circle circle2.setStrokeWidth(20); //Creating the translation transformation Translate translate = new Translate(); //Setting the X,Y,Z coordinates to apply the translation translate.setX(300); translate.setY(50); translate.setZ(100); //Adding transformation to circle2 circle2.getTransforms().addAll(translate); //Creating a Group object Group root = new Group(circle,circle2); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Translation transformation example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 TranslationExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls TranslationExample Output On executing, the above program generates a JavaFX window as shown below. Example 2 In the following example, we are demonstrating translation on 3D shapes. Save this code in a file with the name TranslationExample3D.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Cylinder; import javafx.scene.transform.Translate; import javafx.stage.Stage; public class TranslationExample3D extends Application { @Override public void start(Stage stage) { Cylinder cy1 = new Cylinder(50, 100); Cylinder cy2 = new Cylinder(50, 100); //Creating the translation transformation Translate translate = new Translate(); //Setting the X,Y,Z coordinates to apply the translation translate.setX(200); translate.setY(150); translate.setZ(100); //Adding transformation to circle2 cy2.getTransforms().addAll(translate); //Creating a Group object Group root = new Group(cy1,cy2); //Creating a scene object Scene scene = new Scene(root, 400, 300); //Setting title to the Stage stage.setTitle(“Translation transformation example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 TranslationExample3D.java java –module-path %PATH_TO_FX% –add-modules javafx.controls TranslationExample3D Output On executing, the above program generates a JavaFX window as shown below. As we can see, with the original position of the cylinder we are not able to clearly see the full image like we do in the translated image. Therefore, translation transformation becomes necessary in cases like these. Print Page Previous Next Advertisements ”;
JavaFX – Home
JavaFX Tutorial Table of content JavaFX Tutorial JavaFX Basic UI Controls JavaFX Shapes JavaFX Effects JavaFX Animations Advantages of JavaFX Why to Learn JavaFX? Who Should Learn JavaFX Prerequisites to Learn JavaFX JavaFX Jobs and Opportunities Frequently Asked Questions about JavaFX PDF Version Quick Guide Resources Job Search Discussion JavaFX Tutorial JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library can run consistently across multiple platforms. The applications developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc. To develop GUI Applications using Java programming language, the programmers rely on libraries such as Advanced Windowing Tool Kit and Swing. After the advent of JavaFX, these Java programmers can now develop GUI applications effectively with rich content. Our JavaFX tutorial helps you learn JavaFX in simple and easy steps so that you can start building the User Interface of your application quickly. It covers all the necessary UI elements of JavaFX for a basic to advanced understanding of JavaFX and to get a feel of how JavaFX works. JavaFX Basic UI Controls JavaFx provides a variety of UI controls that allow a smooth interaction between users and applications. These controls are listed below − S.No Control & Description 1 Label It is a component for displaying text. 2 Button It is a class used for creating buttons. 3 Menu Contains a list of commands or options. 4 ToolTip A pop-up window that displays some additional information about other UI elements. 5 TextField Accepts and displays user input. JavaFX Shapes Shapes are geometric figures that can be drawn on either the XY or XYZ plane. Those built on XY plane are called 2D shapes, while those drawn on XYZ plane are referred to as 3D shapes. JavaFx provides various pre-defined classes that represents different types of shapes. These classes are as follows − S.No Class & Description 1 Line It is a class that represents a line. In general, line is a two-dimensional geometrical shape consist of two points. 2 Rectangle It is a class used for creating a 2D rectangular shape. In mathematical terms, rectangle is a four-sided polygon. 3 Box This JavaFX class represents a three-dimensional shape having length, width and height. 4 Cylinder It is a JavaFX class used to create a Cylinder. In general, cylinder is a closed solid figure that has two properties namely radius and height. JavaFX Effects In JavaFx, effects are used to enhance the visual appearance of nodes. The list of effects used in JavaFx are as follows − S.No Effect & Description 1 ColorAdjust It is used to apply colour effects to the JavaFx nodes. 2 Blend In this effect, we combine two or more elements to enhance the visuals. 3 Bloom When we apply this effect to any JavaFx node, then some portion of that node will glow. 4 Reflection This effect will add a reflection at the bottom of node. JavaFX Animations Generally, animations are used to create special visual effects to the elements like images, text, drawings, etc. The most commonly used animations in JavaFx are listed below − S.No Animation & Description 1 Rotate Transition It is used to deal with an object”s position by retaining its shape and properties. 2 Fade Transition This type of animation is done by changing the opacity property of nodes. 3 Stroke Transition It is applied to change the stroke color of a given shape. 4 Scale Transition It is a type animation in which we either increase or decrease the size of an object. Advantages of JavaFX JavaFX offers many advantages over other UI frameworks, such as Swing or AWT. Some of these advantages are as follows − JavaFX supports a declarative syntax for defining UI components, called FXML, which can be easily edited by designers or developers. It supports CSS for styling and animating UI elements, which gives more flexibility and control over the look and feel of the application. It allows us to use a wide range of media formats, such as images, audio, video, and 3D graphics, which can be integrated seamlessly into the UI. Since it is a Java based technology, it also has built-in support for concurrency and multithreading, which enables the application to handle complex tasks without blocking the UI thread. JavaFX also supports binding and properties, which simplifies the communication between the UI and the business logic. Why to Learn JavaFX? JavaFX is a cross-platform and portable framework that allows developers to write an application once and run it on any platform that supports Java. It simplifies UI development with its declarative syntax, FXML, and a rich set of libraries. We can customize a JavaFX application through CSS. Additionally, it supports the creation of dynamic UI effects. As an open-source project, JavaFX is actively developed and maintained by Oracle and the huge Java community. JavaFX is fairly easy to learn, so if you are starting to learn how to develop the user interface of an application then it is very much advised that you should also familiarize yourself with JavaFX. Who Should Learn JavaFX This JavaFX tutorial will help both students as well as working professionals who want to develop Rich Internet Applications. We recommend reading this tutorial, in the sequence listed in the left-side menu. This tutorial has been prepared to cover topics from beginner to advanced level. Prerequisites to Learn JavaFX Though we have tried our best to prepare this JavaFX tutorial in a simple and easy way, still before you start learning JavaFX concepts given in this tutorial, it is assumed that the readers have a prior knowledge of Java programming language. This tutorial will give you enough understanding of the various concepts of JavaFX along with suitable examples so that you can start your User Interface development journey immediately after finishing this tutorial. JavaFX Jobs and Opportunities Professionals skilled in JavaFX are in high demand as the need to develop rich and
JavaFX – InnerShadow Effect
JavaFX – InnerShadow Effect ”; Previous Next While the drop shadow effect creates a duplicate no behind the original node by blurring its edges, the inner shadow effect will be create a shadow inside the edges of the node. They are both similar to shadow effect. The class named InnerShadow of the package javafx.scene.effect represents the inner shadow effect. This class contains ten properties, which are − color − This property is of Color type representing the color of the shadow. blur type − This property is of BlurType and it represents the type of blur effect used to blur the shadow. radius − This property is of the type double and it represents the radius of the shadow blur kernel. width − This property is of the type double and it represents the width of the shadow blur kernel. height − This property is of the type double and it represents the height of the shadow blur kernel. input − This property is of the type Effect and it represents an input to the shadow effect. spread − This property is of the type double; it represents the spread of the shadow. offsetX − This property is of the type double, it represents the shadow offset in the x direction, in pixels. offsetY − This property is of the type double, it represents the shadow offset in the y direction in pixels. choke − This property is of double type; it represents the choke of the shadow. Example The following program is an example demonstrating the inner shadow effect of JavaFX. In here, we are drawing a text “Welcome to Tutorialspoint”, and a circle in a scene. To these, we are applying the inner shadow effect. Save this code in a file with the name InnerShadowEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.InnerShadow; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class InnerShadowEffectExample extends Application { @Override public void start(Stage stage) { //Creating a Text object Text text = new Text(); //Setting font to the text text.setFont(Font.font(null, FontWeight.BOLD, 40)); //setting the position of the text text.setX(60); text.setY(50); //Setting the text to be embedded. text.setText(“Welcome to Tutorialspoint”); //Setting the color of the text text.setFill(Color.RED); //Drawing a Circle Circle circle = new Circle(); //Setting the center of the circle circle.setCenterX(300.0f); circle.setCenterY(160.0f); //Setting the radius of the circle circle.setRadius(100.0f); //setting the fill color of the circle circle.setFill(Color.CORNFLOWERBLUE); //Instantiating the InnerShadow class InnerShadow innerShadow = new InnerShadow(); //Setting the offset values of the inner shadow innerShadow.setOffsetX(4); innerShadow.setOffsetY(4); //Setting the color of the inner shadow innerShadow.setColor(Color.GRAY); //Applying inner shadow effect to the text text.setEffect(innerShadow); //Applying inner shadow effect to the circle circle.setEffect(innerShadow); //Creating a Group object Group root = new Group(text,circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Inner shadow effect example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } 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 InnerShadowEffectExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls InnerShadowEffectExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;