JavaFX – 2D Shapes(Objects) Operations ”; Previous Next Geometrically, a 2D shape is defined as any figure that can be displayed on a two-dimensional plane. Various applications these days make use of such shapes to develop an element or improve the look of their interface. For example, consider any mobile game application. These games contain various 2D shapes on their interface in order to enhance the user experience of the game. Or, a template editor where several 2D shapes are used to give options to the application user. JavaFX provides various nodes to create these 2D shapes like Line, Circle, Rectangle, other Polygons etc. However, to offer permutations and combinations of these shapes, JavaFX also allows you to perform some operations on them. In this chapter, let us briefly learn more about the operations provided. JavaFX Operations on 2D Shapes JavaFX provides various operations mainly to create complex shapes from the simpler shapes. For instance, we learned how to draw a house in the previous chapters of 2D shapes. We had to use several shapes like rectangles, lines etc. to create the final complex house shape; by making use of these operations, we can either merge two shapes easily or remove some area from it. There are three operations available in JavaFX that can be performed on 2D shapes. They are listed below − Union Operation Intersection Operation Subtraction Operation Usually, 2D shapes have a certain area they cover in an application. These three operations are performed on the area covered by these shapes by adding the area together, or subtracting a shape area from another shape, etc. Union Operation Union Operation is generally defined as the combination of two or more elements in an application. In JavaFX, a union operation can be performed on 2D shapes where two or more shapes are taken as inputs and combines the area of them together. This operation is fundamentally represented in the form of a following venn diagram − Intersection Operation Intersection operation retains the common elements from two or more sets. When used with 2D shapes in JavaFX, the common area of two or more shapes will be retained. This is also known as the intersected area of the objects. Look at the image shown below for better understanding. Subtraction Operation Subtraction Operation, also known as the Difference Operation, subtracts the elements of one set from another set. If some elements are not present in the first set (the set from which another set is being subtracted), they are ignored. In JavaFX, an area of a 2D shape is subtracted from the area of another 2D shape as long as they intersect. Print Page Previous Next Advertisements ”;
Category: javafx
JavaFX – ProgressIndicator
JavaFX – ProgressIndicator ”; Previous Next A progress indicator is a UI control that is used to indicate the progress of a task to the user. It is often used with the Task API to notify users about the progress of background tasks and how much time will be required to complete the user action. In this tutorial, we are going to learn how to create and use progress indicator in JavaFX. Before that, let”s see how a general progress indicator looks like − ProgressIndicator in JavaFX In JavaFX, the progress indicator is represented by a class named ProgressIndicator. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a progress indicator in JavaFX. Constructors of the ProgressIndicator class are listed below − ProgressIndicator() − It constructs a new progress indicator without initial progress value. ProgressIndicator(double progress) − It constructs a new progress indicator with a specified initial progress value. Example The following program demonstrates how to create a progress indicator in JavaFX. Save this code in a file with the name ProgressindicatorJavafx.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ProgressIndicator; import javafx.stage.Stage; public class ProgressindicatorJavafx extends Application { @Override public void start(Stage stage) { // Creating a progress indicator without an initial progress value ProgressIndicator progress = new ProgressIndicator(); // Create a scene and stage Scene scene = new Scene(progress, 400, 300); stage.setScene(scene); stage.setTitle(“Progress Indicator in Javafx”); stage.show(); } public static void main(String[] args) { launch(args); } } To compile and execute the saved Java file from the command prompt, use the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls ProgressindicatorJavafx.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ProgressindicatorJavafx Output When we execute the above code, it will generate the following output. ProgressIndicator with an Initial Progress Value We can set the initial progress value to the progress indicator by using the parameterized constructor of the ProgressIndicator class. The constructor accepts a progress value as an argument which is of double type ranging between 0.0 and 1.0. Here, 0.0 means no progress and 1.0 means complete. If the progress value is negative, the progress indicator is indeterminate, meaning that it does not show any specific progress amount. Example In the following example, we are creating a progress indicator initialized with a specific progress value. Additionally, we are also creating two buttons labelled ”Increase” and ”Decrease”. Clicking the ”Increase” button increments the progress value, while clicking ”Decrease” decrements it. Save this code in a file with the name Javafxprogress.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.ProgressIndicator; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class Javafxprogress extends Application { @Override public void start(Stage stage) { // Create a progress indicator with an initial progress of 0.5 ProgressIndicator progressIndctr = new ProgressIndicator(0.5); // Create a button that increases the progress by 0.1 Button buttonOne = new Button(“Increase”); buttonOne.setOnAction(e -> { // Get the current progress value double progress = progressIndctr.getProgress(); // Increase the progress by 0.1 progress += 0.1; // Set the new progress value progressIndctr.setProgress(progress); }); // Create second button that decreases the progress by 0.1 Button buttonTwo = new Button(“Decrease”); buttonTwo.setOnAction(e -> { // Get the current progress value double progress = progressIndctr.getProgress(); // Decrease the progress by 0.1 progress -= 0.1; // Set the new progress value progressIndctr.setProgress(progress); }); // Create an HBox to hold the progress indicator and the button HBox hbox = new HBox(10); hbox.getChildren().addAll(progressIndctr,buttonOne, buttonTwo); // Create a scene with the HBox and set it to the stage Scene scene = new Scene(hbox, 400, 300); stage.setScene(scene); stage.setTitle(“Progress Indicator in JavaFX”); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file from the command prompt by using the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls Javafxprogress.java java –module-path %PATH_TO_FX% –add-modules javafx.controls Javafxprogress Output On executing the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – QuadCurveTo Path Object ”; Previous Next 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 − public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating a Path object Path path = new Path(); } } 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 = new MoveTo(); 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 = new QuadCurveTo() 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. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.QuadCurveTo; public class QuadCurveToExample extends Application { @Override public void start(Stage stage) { //Creating an object of the class named Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0); moveTo.setY(150.0); //Instantiating the class QuadCurve QuadCurveTo quadCurveTo = new QuadCurveTo(); //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 = new Group(path); //Creating a scene object Scene scene = new Scene(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(); } 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 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. 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. import javafx.application.Application; import javafx.animation.FadeTransition; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.QuadCurveTo; import javafx.util.Duration; public class QuadCurveToAnimation extends Application { @Override public void start(Stage stage) { //Creating an object of the class named Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0); moveTo.setY(150.0); //Instantiating the class QuadCurve QuadCurveTo quadCurveTo = new QuadCurveTo(); //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
JavaFX – ChoiceBox
JavaFX – ChoiceBox ”; Previous Next A ChoiceBox is a drop-down list of predefined choices that allows users to select one of them at a time. It always displays the currently selected option on the top of the box, and when the user clicks on the ChoiceBox, it shows a drop-down list of all other available choices. In JavaFX, a choicebox is represented by a class named ChoiceBox. This class belongs to the package javafx.scene.control. By instantiating this class, we can create an ChoiceBox node in JavaFX. Two constructors are available for this class, and they are as follows − ChoiceBox() − It is used for creating an accordion without TitledPane. ChoiceBox(ObservableList items) − It will create an accordion with the specified TitledPane. Creating a Choice Box in JavaFX We need to follow the steps given below to create a ChoiceBox in JavaFX. Step 1: Instantiate the ChoiceBox class In JavaFX, the choice boxes are created by instantiating the class named ChoiceBox which belongs to a package javafx.scene.control. Instantiate this class inside the start() method as shown below − //Instantiating the ChoiceBox class ChoiceBox<String> box = new ChoiceBox<String>(); Step 2: Add Items to the ChoiceBox We use the ObservableList to add the items to a ChoiceBox in JavaFX. It holds all the items with specified type such as String. //Retrieving the observable list ObservableList<String> oslist = box.getItems(); //Adding items to the list oslist.addAll(“Windows7”, “Windows8”, “Windows10”, “Windows11”, “MAC OS”); Note − Sometimes, we may require to specify additional description for ChoiceBox, in such cases, we can use the Label or TextField class of JavaFX. Step 3: Launch the Application Once the ChoiceBox is created and its items are added, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the ChoiceBox object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor. 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 The following JavaFX program demonstrates how to use a ChoiceBox in a JavaFX application. Save this code in a file with the name JavafxChoiceBox.java. import javafx.application.Application; import javafx.collections.ObservableList; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.stage.Stage; public class JavafxChoiceBox extends Application { public void start(Stage stage) { //Instantiating the ChoiceBox class ChoiceBox<String> box = new ChoiceBox<String>(); //Retrieving the observable list ObservableList<String> oslist = box.getItems(); //Adding items to the list oslist.addAll(“Windows7”, “Windows8”, “Windows10”, “Windows11”, “MAC OS”); //Setting the position of the choice box box.setTranslateX(200); box.setTranslateY(15); //Setting the label Label setlabel = new Label(“Select your Operating System:”); setlabel.setTranslateX(20); setlabel.setTranslateY(20); //Adding the choice box to the group Group newgrp = new Group(box, setlabel); //Setting the stage Scene scene = new Scene(newgrp, 500, 200); stage.setTitle(“Choice Box in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } To compile and execute the saved Java file from the command prompt, use the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxChoiceBox.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxChoiceBox Output When we execute the above code, it will generate the following output. Creating a Choice Box using its Parameterized Constructor Previously, we have used the empty constructor of the ChoiceBox class to create a choice box. However, there is also another way available for the same. We can use the parameterized constructor by passing the list items using observableArrayList as an argument. Example Following is the JavaFX program which will create a Choice Box using Parameterized Constructor of ChoiceBox class. Save this code in a file with the name JavafxChoiceBox.java. import javafx.application.Application; import javafx.collections.*; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.ChoiceBox; import javafx.scene.control.Label; import javafx.stage.Stage; public class JavafxChoiceBox extends Application { public void start(Stage stage) { //Creating a ChoiceBox ChoiceBox<String> box = new ChoiceBox<String> ( FXCollections.observableArrayList( “Windows7”, “Windows8”, “Windows10”, “Windows11”, “MAC OS”)); //Setting the position of the choice box box.setTranslateX(200); box.setTranslateY(15); //Setting the label Label setlabel = new Label(“Select your Operating System:”); setlabel.setTranslateX(20); setlabel.setTranslateY(20); //Adding the choice box to the group Group newgrp = new Group(box, setlabel); //Setting the stage Scene scene = new Scene(newgrp, 500, 200); stage.setTitle(“Choice Box in JavaFX”); stage.setScene(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 JavafxChoiceBox.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxChoiceBox Output On executing, the above program generates a JavaFX window displaying the below output. Print Page Previous Next Advertisements ”;
JavaFX – Stroke Property
JavaFX – Stroke Property ”; Previous Next The Stroke Fill property is used to change the colours of 2D object itself. However, we can also change the colour of a 2D object”s boundary. In JavaFX, while creating a 2D object, there are only two parts you can work with, if you want to improve the quality of the shape; i.e., the enclosed area of the shape and the boundary of the shape. Hence, the properties provided by JavaFX include designing both these parts. In this chapter, we will learn about the Stroke property in detail. Stroke Property The Stroke property in JavaFX is used to change colours of the shape boundary. This property is of the type Paint and it represents the color of the boundary line of the shape. You can set a value to this property using the method setStroke(). This method is a part of javafx.scene.paint package and takes the Color object as a parameter value as shown below − path.setStroke(Color.RED) By default, the color of the stroke is black. Following is a diagram of a triangle with different stroke colors. Example We will see an example demonstrating how to colour the boundary of a 2D shape in JavaFX. In here, we are drawing a 2D shape, say a rectangle. By default, the rectangle will be coloured black; we will try to change its boundary colour to Violet. Save the file with the name StrokeExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Shape; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeExample extends Application { @Override public void start(Stage stage) { //Creating a Rectangle Rectangle rectangle = new Rectangle(50.0f, 50.0f, 200.0f, 100.0f); rectangle.setStroke(Color.VIOLET); rectangle.setStrokeWidth(7.0); //Creating a Group object Group root = new Group(rectangle); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Rectangle”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 StrokeExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeExample Output On executing, the above program generates a JavaFX window displaying a rectangle with a stroke coloured violet as shown below. Example In this example, we are drawing a polygon and change its boundary colour to RED. Save the file with the name StrokePolygonExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.scene.shape.Shape; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokePolygonExample extends Application { @Override public void start(Stage stage) { //Creating a Polygon Polygon polygon = new Polygon(); //Adding coordinates to the polygon polygon.getPoints().addAll(new Double[]{ 100.0, 50.0, 200.0, 50.0, 250.0, 150.0, 200.0, 250.0, 100.0, 250.0, }); polygon.setStroke(Color.RED); polygon.setStrokeWidth(5.0); //Creating a Group object Group root = new Group(polygon); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Polygon”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 StrokePolygonExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokePolygonExample Output On executing, the above program generates a JavaFX window displaying a rectangle with a stroke coloured violet as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Drawing an SVGPath
JavaFX – Drawing an SVGPath ”; Previous Next SVG (Scalable Vector Graphics) is an XML based language to define vector based graphics. The <path> element in the SVG library is the most powerful while drawing basic shapes. Using paths, you can draw lines, curves, arcs, and also various complex shapes including them. Even though a path is similar to the polyline element while creating complex shapes, the scale of complex shapes drawn using a polyline element is not larger than shapes drawn using path element. A path in SVG is defined by only one parameter. This parameter holds series of commands, like line, curve or arc commands. And each of these commands are instantiated using a single letter; for example, the letter ”M” calls the “Move To” command, the letter ”L” calls the “line” command and ”C” calls “Curve” command. And these letters can either be specified as either a lowercase or an uppercase letter. The lowercase letter specifies relative coordinates, while the uppercase letter specifies absolute coordinates. The same concept of SVGPath is adopted by JavaFX, in order to create objects. SVG Path in JavaFX In JavaFX we can construct images by parsing SVG paths. Such shapes are represented by the class named SVGPath. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a node which is created by parsing an SVG path in JavaFX. This class has a property named content of String datatype. This represents the SVG Path encoded string, from which the image should be drawn. To draw a shape by parsing an SVG path, you need to pass values to this property, using the method named setContent() of this class as follows − setContent(value); Steps to Draw SVGPath To Draw a shape by parsing an SVGPath in JavaFX, follow the steps given below. Step 1: Creating an Object of the SVGPath Class You can create a required shape in JavaFX by parsing an SVGPath. To do so, instantiate the class named SVGPath which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method as follows. public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { //Creating an object of the class SVGPath SVGPath svgpath = new SVGPath(); } } Step 2: Setting the SVGPath Set the content for the SVG object using the method setContent(). To this method, you need to pass the SVGPath. Using which, a shape should be drawn in the form of a string as shown in the following code block. String path = “M 100 100 L 300 100 L 200 300 z”; //Setting the SVGPath in the form of string svgPath.setContent(path); Step 3: Adding SVGPath to Group In the start() method, instantiate the Group class by passing the SVGPath object as a parameter value to its constructor − Group root = new Group(svgpath); Step 4: Launching Application Once the 2D object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is a program which generates a 2D shape constructed with lines by parsing SVG path using JavaFX. Save this code in a file with the name SVGExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.SVGPath; import javafx.stage.Stage; public class SVGExample extends Application { @Override public void start(Stage stage) { //Creating a SVGPath object SVGPath svgPath = new SVGPath(); String path = “M 100 100 L 300 100 L 200 300 z”; //Setting the SVGPath in the form of string svgPath.setContent(path); //Creating a Group object Group root = new Group(svgPath); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Triangle”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 SVGExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SVGExample Output On executing, the above program generates a JavaFX window displaying a triangle, which is drawn by parsing the SVG path as shown below. Example You can also construct complex shapes from curves and arcs using an SVG path. Following example creates a cubic curve using an SVG Path. Save this code in a file with the name SVGCurveExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.SVGPath; import javafx.stage.Stage; public class SVGCurveExample extends Application { @Override public void start(Stage stage) { //Creating a SVGPath object SVGPath svgPath = new SVGPath(); String path = “M 70 110 C 70 180, 210 180, 210 110”; //Setting the SVGPath in the form of string svgPath.setContent(path); // Setting the stroke and fill of the path svgPath.setStroke(Color.BLACK); svgPath.setFill(Color.ORANGE); //Creating a Group object Group root = new Group(svgPath); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Bezier Curve”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 SVGCurveExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SVGCurveExample Output On executing, the above program generates a JavaFX window displaying a triangle, which is drawn by parsing the SVG path as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Drawing Modes Property ”; Previous Next You can draw 3D shapes in a JavaFX application using the Shape3D class. This class allows you construct three types of 3D shapes: box, cylinder, sphere as its direct subclasses. However, according to the nature of a JavaFX application you are trying to create, you can also enhance the look of a 3D shape using the properties the Shape3D class provides. There are three such properties that can be applied on 3D shapes of a JavaFX application. They are listed as follows − Cull Face Property Drawing Modes Property Material Property In this chapter, we will be learning about the Drawing Modes Property in JavaFX. Drawing Modes Property Drawing Modes is the property that belongs to the DrawMode enum type and it represents the type of drawing mode used to draw the current 3D shape. In JavaFX, you can choose two draw modes to draw a 3D shape, which are − Fill − This mode draws and fills a 2D shape (DrawMode.FILL). Line − This mode draws a 3D shape using lines (DrawMode.LINE). By default, the drawing mode of a 3Dimensional shape is fill. But you can still choose the draw mode to draw a 3D shape using the method setDrawMode() as follows − box.setDrawMode(DrawMode.FILL); Example The following program is an example which demonstrates the LINE draw mode on a 3D box. Save this code in a file with the name BoxDrawModeLine.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.scene.shape.DrawMode; import javafx.stage.Stage; public class BoxDrawModeLine extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box1 = new Box(); //Setting the properties of the Box box1.setWidth(100.0); box1.setHeight(100.0); box1.setDepth(100.0); //Setting the position of the box box1.setTranslateX(200); box1.setTranslateY(150); box1.setTranslateZ(0); //Setting the drawing mode of the box box1.setDrawMode(DrawMode.LINE); //Creating a Group object Group root = new Group(box1); //Creating a scene object Scene scene = new Scene(root, 300, 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 BoxDrawModeLine.java java –module-path %PATH_TO_FX% –add-modules javafx.controls BoxDrawModeLine Output On executing, the above program generates a JavaFX window displaying a box with draw mode LINE, as follows − Example Let us now see another example that shows the usage of FILL draw mode on a 3D shape. To show the difference of these modes properly, we will again apply this mode on a 3D box. Save this code in a file with the name BoxDrawModeFill.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.shape.Box; import javafx.scene.shape.DrawMode; import javafx.stage.Stage; public class BoxDrawModeFill extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box1 = new Box(); //Setting the properties of the Box box1.setWidth(100.0); box1.setHeight(100.0); box1.setDepth(100.0); //Setting the position of the box box1.setTranslateX(200); box1.setTranslateY(150); box1.setTranslateZ(0); //Setting the drawing mode of the box box1.setDrawMode(DrawMode.FILL); //Creating a Group object Group root = new Group(box1); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting camera PerspectiveCamera camera = new PerspectiveCamera(false); camera.setTranslateX(100); camera.setTranslateY(50); camera.setTranslateZ(0); scene.setCamera(camera); //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 BoxDrawModeFill.java java –module-path %PATH_TO_FX% –add-modules javafx.controls BoxDrawModeFill Output On executing, the above program generates a JavaFX window displaying a box with draw mode FILL, as follows − Print Page Previous Next Advertisements ”;
JavaFX – ButtonBar
JavaFX – Button Bar ”; Previous Next A ButtonBar is a type of container that arranges buttons in a horizontal layout. The arrangement or positions of these buttons depend on the type of operating system we are working on. Generally, all the buttons placed inside a ButtonBar are uniformly sized. However, it also allows us to customize the size as well as positions of the buttons. A typical button bar looks like the below figure. It contains two buttons namely “Yes” and “No”. ButtonBar in JavaFX In JavaFX, the class named ButtonBar represents a button bar. This class belongs to the package javafx.scene.control. We can create a button bar node in JavaFX by instantiating the ButtonBar class. There are two constructors available for this class, and they are as follows − ButtonBar() − It is used for creating a button bar with default properties that will be specific to the operating system. ButtonBar(String buttonOrder) − It will create a button bar with the specified button order. Steps to create a Button Bar in JavaFX To create a Button Bar in JavaFX, follow the steps given below. Step 1: Create two or more Buttons In JavaFX, the buttons are created by instantiating the class named Button which belongs to a package javafx.scene.control. Instantiate this class as shown below − //Creating required buttons Button buttonOne = new Button(“Back”); Button buttonTwo = new Button(“Accept”); Button buttonThree = new Button(“Cancel”); Similarly, create the required number of buttons for the project. Step 2: Instantiate ButtonBar class Instantiate the ButtonBar class of package javafx.scene.control without passing any parameter value to its constructor and add all the buttons using the getButtons() method. //Creating a ButtonBar ButtonBar newButtonbar = new ButtonBar(); // Adding buttons to the ButtonBar newButtonbar.getButtons().addAll(buttonOne, buttonTwo, buttonThree); Step 3: Launching Application After creating the button bar, follow the given steps below to launch the application properly − Firstly, instantiate the class named HBox and add the button bar using getChildren() method. Then, instantiate the class named Scene by passing the HBox object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor. 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 will create a button bar in JavaFX. Save this code in a file with the name JavafxButtonBar.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ButtonBar; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class JavafxButtonBar extends Application { @Override public void start(Stage stage) { //Creating required buttons Button buttonOne = new Button(“Back”); Button buttonTwo = new Button(“Accept”); Button buttonThree = new Button(“Cancel”); //Creating a ButtonBar ButtonBar newButtonbar = new ButtonBar(); // Adding buttons to the ButtonBar newButtonbar.getButtons().addAll(buttonOne, buttonTwo, buttonThree); newButtonbar.setPadding(new Insets(10)); HBox box = new HBox(); box.getChildren().addAll(newButtonbar); //Setting the stage Scene scene = new Scene(box, 500, 250); stage.setTitle(“ButtonBar in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } Compile and execute the above Java file using the command prompt with the help of following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxButtonBar.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxButtonBar Output On executing, the above program generates a JavaFX window displaying a ButtonBar as shown below. Creating a ButtonBar with customized Button orders In most cases, the order of the Buttons is determined by the operating system. But, if a custom layout is required, then, the setButtonOrder() method of the ButtonBar class can be used. It takes button order property as a parameter and arranges the buttons accordingly. The button order properties of different OS are BUTTON_ORDER_WINDOWS, BUTTON_ORDER_MAC_OS, and BUTTON_ORDER_LINUX. Example In the following JavaFX program, we will create a ButtonBar by setting the button order property of MAC. Save this code in a file with the name JavafxButtonBar.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonBar.ButtonData; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.stage.Stage; public class JavafxButtonBar extends Application { @Override public void start(Stage stage) { //Creating required buttons Button buttonTwo = new Button(“Yes”); Button buttonOne = new Button(“No”); //Creating a ButtonBar ButtonBar newButtonbar = new ButtonBar(); // Setting the order of Buttons newButtonbar.setButtonOrder(“BUTTON_ORDER_MAC_OS”); // Adding buttons to the ButtonBar newButtonbar.getButtons().addAll(buttonOne, buttonTwo); newButtonbar.setPadding(new Insets(10)); HBox box = new HBox(); box.getChildren().addAll(newButtonbar); //Setting the stage Scene scene = new Scene(box, 500, 250); stage.setTitle(“ButtonBar in JavaFX”); stage.setScene(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 JavafxButtonBar.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxButtonBar Output When we execute the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – Creating a Sphere
JavaFX – Creating a Sphere ”; Previous Next A sphere is a perfectly round geometrical object in a three-dimensional space that is the surface of a completely round shaped ball. A sphere is defined as the set of points that are all at the same distance r from a given point in a 3D space. This distance r is the radius of the sphere and the given point is the centre of the sphere. Sphere in JavaFX In JavaFX, a sphere is represented by a class named Sphere. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a sphere node in JavaFX. This class has a property named radiusof double datatype. It represents the radius of a Sphere. To draw a Sphere, you need to set values to this property by passing it to the constructor of this class at the time of instantiation; Or, by using a setter method named setRadius(). Steps to Draw 3D Sphere Follow the steps given below to Draw a Sphere (3D) in JavaFX. Step 1: Creating a Sphere Create a Sphere in JavaFX by instantiating the class named Sphere, which belongs to a package javafx.scene.shape. You can instantiate this class in the start() method as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating an object of the class Sphere Sphere sphere = new Sphere(); } } Step 2: Setting Properties to the Sphere Set the radius of the Sphere using the method named setRadius() as shown below. //Setting the radius of the Sphere sphere.setRadius(300.0); Step 3: Creating a Group Object Instantiate the Group class by passing sphere object as a parameter to its constructor, as shown below − Group root = new Group(sphere); 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 The following program shows how to generate a Sphere using JavaFX. Save this code in a file with the name SphereExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Sphere; public class SphereExample extends Application { @Override public void start(Stage stage) { //Drawing a Sphere Sphere sphere = new Sphere(); //Setting the properties of the Sphere sphere.setRadius(50.0); sphere.setTranslateX(200); sphere.setTranslateY(150); //Creating a Group object Group root = new Group(sphere); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Sphere – draw fill”); //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 SphereExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SphereExample Output On executing, the above program generates a JavaFX window displaying a Sphere as shown below. Example In the following program, we are applying some CSS in JavaFX by colouring the scene of JavaFX application. Save this code in a file with the name CSSSphereExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.paint.Color; import javafx.scene.shape.Sphere; public class CSSSphereExample extends Application { @Override public void start(Stage stage) { //Drawing a Sphere Sphere sphere = new Sphere(); //Setting the properties of the Sphere sphere.setRadius(50.0); sphere.setTranslateX(100); sphere.setTranslateY(150); //Creating a Group object Group root = new Group(sphere); //Creating a scene object Scene scene = new Scene(root, 300, 300); scene.setFill(Color.ORANGE); //Setting title to the Stage stage.setTitle(“Drawing a Sphere”); //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 CSSSphereExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CSSSphereExample Output On executing, the above program generates a JavaFX window displaying a Sphere as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Stroke Fill Property ”; Previous Next JavaFX application supports displaying diverse content like text, 2D shapes, 3D shapes, etc.; and every object has a default setting in order to create a basic application. Hence, while drawing 2D shapes on a JavaFX application, each shape also has some default settings that can be modified when they are set separately. For instance, the default fill colour in a 2D shape is always black. Various properties are introduced to improve the quality of these shapes; and we have already learned how to change the dimensions and placement of the shape boundaries, in previous chapters. In this chapter, we will learn how to change the default colour black of a specific 2D shape to other colours. Stroke Fill Property Stroke Fill property in JavaFX 2D shapes is used to specify the colour which a shape is to be filled with. This property belongs to the javafx.scene.paint package. You can set the fill color of a shape using the method setFill() as follows − path.setFill(COLOR.BLUE); By default, the value of the stroke color is BLACK. Following is a diagram of a triangle with different colors. Example In this example, we will try to create two 2D circles, and fill one of the circle with Yellow colour and another will maintain its default colour. The aim is to observe the difference between both shapes. Save this file with the name StrokeFillExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeFillExample extends Application { @Override public void start(Stage stage) { //Creating a Circle Circle circle1 = new Circle(200.0f, 150.0f, 50.0f); Circle circle2 = new Circle(100.0f, 150.0f, 50.0f); circle1.setFill(Color.YELLOW); //Creating a Group object Group root = new Group(); root.getChildren().addAll(circle1, circle2); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Colouring a Circle”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 StrokeFillExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeFillExample Output On executing, the above program generates a JavaFX window displaying two circles, the left one having its default fill while the other one is yellow coloured, as shown below. Example We created two simple 2D shapes in the previous example, but you can also set a fill color to complex shapes created using path element. In this example, we are trying to fill a complex shape created using line commands of SVG Path. Save this file with the name StrokeFillSVGPath.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.SVGPath; import javafx.stage.Stage; public class StrokeFillSVGPath extends Application { @Override public void start(Stage stage) { //Creating a SVGPath object SVGPath svgPath = new SVGPath(); String path = “M 100 100 H 190 V 190 H 150 L 200 200”; //Setting the SVGPath in the form of string svgPath.setContent(path); // Setting the stroke and fill of the path svgPath.setStroke(Color.BLACK); svgPath.setFill(Color.BLUE); //Creating a Group object Group root = new Group(svgPath); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Line”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 StrokeFillSVGPath.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeFillSVGPath Output On executing, the above program generates a JavaFX window displaying two circles, the left one having its default fill while the other one is yellow coloured, as shown below. Print Page Previous Next Advertisements ”;