JavaFX – HTMLEditor

JavaFX – HTMLEditor ”; Previous Next An HTML editor is a type of text editor where users can create and edit HTML code within the JavaFX application. Some of the popular HTML text editors include Notepad, Sublime Text, Atom, Vscode and so on. Note − The HTML is a markup language used for developing web applications. In JavaFX, the HTML editor is represented by a class named HTMLEditor. This class belongs to the package javafx.scene.web. By instantiating this class, we can embed an HTMLEditor node in JavaFX. The JavaFX HTMLEditor provides the following features − It supports text indentation and alignment. We can create bulleted as well as numbered lists. It allows us to change the background and foreground colors. It also includes text styling features such as colors, bold, italic and underline. We can also set the font size and font family. Embedding an HTMLEditor in JavaFX As mentioned earlier, we can directly embed an HTML editor within the JavaFX application by instantiating the HTMLEditor class. Similar to other UI controls, it is necessary to add the HTMLEditor instance to the Scene object to make it visible in the JavaFX application. Example The following JavaFX program demonstrates how to embed an HTML editor into a JavaFX application. Save this code in a file with the name JavafxHtmlEditor.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.stage.Stage; import javafx.scene.web.HTMLEditor; public class JavafxHtmlEditor extends Application { @Override public void start(Stage stage) { // Instantiating HTMLEditor class HTMLEditor editorhtml = new HTMLEditor(); // including the HTMLEditor to Scene Scene scene = new Scene(editorhtml, 600, 500); // setting the stage to display editor stage.setScene(scene); stage.setTitle(“HTML Editor 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,javafx.web JavafxHtmlEditor.java java –module-path %PATH_TO_FX% –add-modules javafx.controls,javafx.web JavafxHtmlEditor Output When we execute the above code, it will generate the following output. Creating an HtmlEditor in JavaFX with predefined Text We can also provide predefined text with desired styling through JavaFX code. For this operation, we can use the setHtmlText() method of the HTMLEditor class. This method takes a String as a parameter and displays that content in the editing area when the JavaFX application starts. Example Following is the JavaFX program which will create an HTML editor with the predefined text. Save this code in a file with the name HtmlEditorText.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.stage.Stage; import javafx.scene.web.HTMLEditor; public class HtmlEditorText extends Application { @Override public void start(Stage stage) { // Instantiating HTMLEditor class HTMLEditor editorhtml = new HTMLEditor(); // Setting the content for HTML Editor String text = “<html><body>Lorem ipsum dolor sit “ + “amet, consectetur adipiscing elit. Nam tortor felis, pulvinar “ + “in scelerisque cursus, pulvinar at ante. Nulla consequat” + “congue lectus in sodales. Nullam eu est a felis ornare.</body></html>”; editorhtml.setHtmlText(text); // including the HTMLEditor to Scene Scene scene = new Scene(editorhtml, 600, 500); // setting the stage to display editor stage.setScene(scene); stage.setTitle(“HTML Editor in JavaFX”); 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,javafx.web HtmlEditorText.java java –module-path %PATH_TO_FX% –add-modules javafx.controls,javafx.web HtmlEditorText Output When we execute the above code, it will generate the following output. Generating HTML code using HtmlEditor in JavaFX The HTMLEditor class provides a method named getHtmlText() to retrieve the content of the editing area. This method is called along with the object of HTMLEditor class. Example In the following JavaFX program, we will create an HTML editor to create and edit content, a button to obtain respective HTML code and a text area to show obtained code. Save this code in a file with the name HtmlgetText.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.*; import javafx.scene.control.*; import javafx.stage.Stage; import javafx.scene.web.HTMLEditor; import javafx.event.ActionEvent; import javafx.geometry.Insets; import javafx.geometry.Pos; public class HtmlgetText extends Application { @Override public void start(Stage stage) { // Instantiating HTMLEditor class HTMLEditor editorhtml = new HTMLEditor(); editorhtml.setPrefHeight(300); // Creating a Text area to show HTML Code TextArea code = new TextArea(); ScrollPane pane = new ScrollPane(); pane.setContent(code); pane.setFitToWidth(true); pane.setPrefHeight(300); // creating button to get code Button button = new Button(“Get Code”); button.setOnAction(a -> { code.setText(editorhtml.getHtmlText()); }); // Creating root VBox root = new VBox(); root.setPadding(new Insets(10)); root.setSpacing(5); root.setAlignment(Pos.BOTTOM_LEFT); root.getChildren().addAll(editorhtml, button, pane); // including the HTMLEditor to Scene Scene scene = new Scene(root, 625, 500); // setting the stage to display editor stage.setScene(scene); stage.setTitle(“HTML Editor in JavaFX”); 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,javafx.web HtmlgetText.java java –module-path %PATH_TO_FX% –add-modules javafx.controls,javafx.web HtmlgetText Output On executing, the above program generates a JavaFX window displaying the below output. Print Page Previous Next Advertisements ”;

JavaFX – Subtraction Operation

JavaFX – Subtraction Operation ”; Previous Next As the name suggests, the subtraction operation will subtract the elements of a set from another set. Most people are generally confused between the intersection operation, the two operations completely differ with respect to their operations. While intersection operation retrieves the common elements between two sets, the subtraction operation finds the common elements between two sets and removes them from the first set. If there are elements in second set that are not present in the first set, they are ignored. Like other operations, the subtraction operation is also adopted in computer programming. It is available as difference operator in few programming languages; but in JavaFX, this operation can be used on 2D shapes. Subtraction Operation in JavaFX In JavaFX, the subtraction operation works with the area covered by two or more 2D shapes. It eliminates the area of the second shape from the area of the first shape. If the areas of these two shapes are fully exclusive, the area of first shape is retained as the result. Technically, this operation takes two or more shapes as an input. Then, it returns the area of the first shape excluding the area overlapped by the second one as shown below. You can perform the Subtraction Operation on the shapes using the method named subtract(). Since this is a static method, you should call it using the class name (Shape or its subclasses) as shown below. Shape shape = Shape.subtract(circle1, circle2); Following is an example of the Subtraction Operation. In here, we are drawing two circles and performing a subtraction operation on them. Save this code in a file with name SubtractionExample.java. Example import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; public class SubtractionExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle1 = new Circle(); //Setting the position of the circle circle1.setCenterX(250.0f); circle1.setCenterY(135.0f); //Setting the radius of the circle circle1.setRadius(100.0f); //Setting the color of the circle circle1.setFill(Color.DARKSLATEBLUE); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(350.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.BLUE); //Performing subtraction operation on the circle Shape shape = Shape.subtract(circle1, circle2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Subtraction 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 SubtractionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SubtractionExample Output On executing, the above program generates a JavaFX window displaying the following output − Example Now, let us try to perform subtraction operation on two ellipses where we will subtract the area of second ellipse from the first ellipse. Save this file under the name EllipseSubtractionOperation.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Shape; public class EllipseSubtractionOperation extends Application { @Override public void start(Stage stage) { Ellipse ellipse1 = new Ellipse(); ellipse1.setCenterX(250.0f); ellipse1.setCenterY(100.0f); ellipse1.setRadiusX(150.0f); ellipse1.setRadiusY(75.0f); ellipse1.setFill(Color.BLUE); Ellipse ellipse2 = new Ellipse(); ellipse2.setCenterX(350.0f); ellipse2.setCenterY(100.0f); ellipse2.setRadiusX(150.0f); ellipse2.setRadiusY(75.0f); ellipse2.setFill(Color.RED); Shape shape = Shape.subtract(ellipse1, ellipse2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Subtraction 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 EllipseSubtractionOperation.java java –module-path %PATH_TO_FX% –add-modules javafx.controls EllipseSubtractionOperation Output On executing, the above program generates a JavaFX window displaying the following output − Print Page Previous Next Advertisements ”;

JavaFX – Intersection Operation

JavaFX – Intersection Operation ”; Previous Next Similar to the Union operation, the intersection operation was fundamentally used in set theory. As the name suggests, this operation is defined as the intersection of two different sets into one. Hence, the common elements from two or more sets are retrieved; ignoring duplicate elements. This concept is then adopted by various techniques in computer programming. For instance, it is also used in programming languages like C, C++, Java, Python etc. as an operator or a method. Similarly, JavaFX also provides intersection operation on 2D shapes. Intersection Operation in JavaFX JavaFX allows you to perform intersection operation on 2D shapes, where, the areas of two or more shapes are intersected together and the common area of these shapes is obtained as a result. Thus, this operation takes two or more shapes as inputs and returns the intersection area between them as shown below. You can perform an intersection operation on the shapes using the method named intersect(). Since this is a static method, you should call it using the class name (Shape or its subclasses) as shown below. Shape shape = Shape.intersect(circle1, circle2); Following is an example of the intersection operation. In here, we are drawing two circles and performing a intersection operation on them. Save this code in a file with the name IntersectionExample.java Example import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; public class IntersectionExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle1 = new Circle(); //Setting the position of the circle circle1.setCenterX(250.0f); circle1.setCenterY(135.0f); //Setting the radius of the circle circle1.setRadius(100.0f); //Setting the color of the circle circle1.setFill(Color.DARKSLATEBLUE); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(350.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.BLUE); //Performing intersection operation on the circle Shape shape = Shape.intersect(circle1, circle2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Intersection 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 IntersectionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls IntersectionExample Output On executing, the above program generates a JavaFX window displaying the following output − Example Now, let us try to perform intersection operation on two elliptical shapes (to retrieve the common area between them). Save this file under the name EllipseIntersectionOperation.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Shape; public class EllipseIntersectionOperation extends Application { @Override public void start(Stage stage) { Ellipse ellipse1 = new Ellipse(); ellipse1.setCenterX(250.0f); ellipse1.setCenterY(100.0f); ellipse1.setRadiusX(150.0f); ellipse1.setRadiusY(75.0f); ellipse1.setFill(Color.BLUE); Ellipse ellipse2 = new Ellipse(); ellipse2.setCenterX(350.0f); ellipse2.setCenterY(100.0f); ellipse2.setRadiusX(150.0f); ellipse2.setRadiusY(75.0f); ellipse2.setFill(Color.RED); Shape shape = Shape.intersect(ellipse1, ellipse2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Intersection 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 EllipseIntersectionOperation.java java –module-path %PATH_TO_FX% –add-modules javafx.controls EllipseIntersectionOperation Output On executing, the above program generates a JavaFX window displaying the following output − Print Page Previous Next Advertisements ”;

JavaFX – MenuBar

JavaFX – MenuBar ”; Previous Next A menubar is a graphical user interface component that displays a horizontal row of menus, each containing a list of commands or options. It is located at the top of a window or screen, and provides a convenient way for users to access the functionality of an application. A typical menubar looks like the below figure − Creating MenuBar in JavaFX In JavaFX, the menubar control is represented by a class named MenuBar. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a MenuBar control in JavaFX. In addition to the MenuBar class, we also require the following classes − Menu The Menu class represents a single menu in the menubar. It has a text property that defines its label, and an items property that holds a list of menu items. To create a Menu, use the code given below − //Creating a menu Menu objectOfMenu = new Menu(“nameOfMenu”); MenuItem The MenuItem is used to create a single command or option within a menu. It has a text property that defines its label, and an onAction property that defines what happens when the user selects it. It is created by using the below code − //Creating menu items for the menu MenuItem menuItemObject = new MenuItem(“nameOfMenuItem”); Example The following example illustrates how to create a MenuBar in JavaFX application. Save this code in a file with the name JavafxmenuBar.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.stage.Stage; public class JavafxmenuBar extends Application { public void start(Stage stage) { //Creating the first menu Menu category = new Menu(“Category”); //Creating menu items for the menu MenuItem itemOne = new MenuItem(“Programming”); MenuItem itemTwo = new MenuItem(“Cyber Security”); MenuItem itemThree = new MenuItem(“Marketing”); //Adding all the items to the category category.getItems().addAll(itemOne, itemTwo, itemThree); //Creating another menu Menu library = new Menu(“Library”); //Creating menu items for the library menu MenuItem itemFour = new MenuItem(“HTML”); MenuItem itemFive = new MenuItem(“Java”); MenuItem itemSix = new MenuItem(“JavaFX”); //Adding all the items to library menu library.getItems().addAll(itemFour, itemFive, itemSix); //Creating the third menu Menu articles = new Menu(“Articles”); //Creating menu items for the articles MenuItem itemSeven = new MenuItem(“Constructor”); MenuItem itemEight = new MenuItem(“Inheritance”); MenuItem itemNine = new MenuItem(“Current Affairs”); //Adding all items to the menu articles.getItems().addAll(itemSeven, itemEight, itemNine); //Instantiating the MenuBar class MenuBar newmenubar = new MenuBar(); //Adding all the menus to the MenuBar object newmenubar.getMenus().addAll(category, library, articles); //Setting the stage Group newgroup = new Group(newmenubar); Scene scene = new Scene(newgroup, 600, 400); stage.setTitle(“MenuBar 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 JavafxmenuBar.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxmenuBar Output When we execute the above code, it will generate the following output. How to add Icons to the MenuItems? To add icons to the menuitems, we call the setGraphic() method which accepts an object of ImageView class. The icon will be appear next to the MenuItem name. Example In the following JavaFX application, we are going to demonstrate how to add icons for the menuitems within MenuBar. Save this code in a file with the name JavafxmenuBar.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Menu; import javafx.scene.control.MenuBar; import javafx.scene.control.MenuItem; import javafx.stage.Stage; import java.io.File; import javafx.scene.image.ImageView; public class JavafxmenuBar extends Application { public void start(Stage stage) { //Creating the first menu Menu category = new Menu(“Category”); //Creating menu items for the menu MenuItem itemOne = new MenuItem(“Programming”); MenuItem itemTwo = new MenuItem(“Cyber Security”); MenuItem itemThree = new MenuItem(“Marketing”); // adding icons to the menuitems itemOne.setGraphic(new ImageView(“file:programming.png”)); itemTwo.setGraphic(new ImageView(“file:cyber.png”)); itemThree.setGraphic(new ImageView(“file:marketing.png”)); //Adding all the items to the category category.getItems().addAll(itemOne, itemTwo, itemThree); //Creating another menu Menu library = new Menu(“Library”); //Creating menu items for the library menu MenuItem itemFour = new MenuItem(“HTML”); MenuItem itemFive = new MenuItem(“Java”); MenuItem itemSix = new MenuItem(“JavaFX”); //Adding all the items to library menu library.getItems().addAll(itemFour, itemFive, itemSix); //Creating the third menu Menu articles = new Menu(“Articles”); //Creating menu items for the articles MenuItem itemSeven = new MenuItem(“Constructor”); MenuItem itemEight = new MenuItem(“Inheritance”); MenuItem itemNine = new MenuItem(“Current Affairs”); //Adding all items to the menu articles.getItems().addAll(itemSeven, itemEight, itemNine); //Instantiating the MenuBar class MenuBar newmenubar = new MenuBar(); //Adding all the menus to the MenuBar object newmenubar.getMenus().addAll(category, library, articles); //Setting the stage Group newgroup = new Group(newmenubar); Scene scene = new Scene(newgroup, 600, 400); stage.setTitle(“MenuBar 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 by using the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxmenuBar.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxmenuBar Output On executing the above JavaFX 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

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 ”;

JavaFX – Drawing an Ellipse

JavaFX – Drawing an Ellipse ”; Previous Next 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. The sum of these distances is equal to the length of the major axis (the longest diameter of the ellipse). A circle is, in fact, a special case of an Ellipse. An Ellipse has three properties which are − Centre − A point inside the Ellipse which is the midpoint of the line segment linking the two foci. The intersection of the major and minor axes. Major axis − The longest diameter of an ellipse. Minor axis − The shortest diameter of an ellipse. Ellipse in JavaFX In JavaFX, an Ellipse is represented by a class named Ellipse. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create an Ellipse node in JavaFX. This class has 4 properties of the double datatype namely − centerX − The x coordinate of the center of the ellipse in pixels. centerY − The y coordinate of the center of the ellipse in pixels. radiusX − The width of the ellipse pixels. radiusY − The height of the ellipse pixels. To draw an ellipse, you need to pass values to these properties, either by passing them to the constructor of this class in the same order, or by using setter methods. Steps to Draw Ellipse Follow the steps given below to draw an Ellipse in JavaFX. Step 1: Creating an Ellipse You can create an Ellipse in JavaFX by instantiating the class named Ellipse which belongs to a package javafx.scene.shape, inside the start() method. You can instantiate this class as follows. public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { //Creating an Ellipse object Ellipse ellipse = new Ellipse(); } } Step 2: Setting Properties to the Ellipse Specify the x, y coordinates of the center of the Ellipse → the width of the Ellipse along x axis and y axis (major and minor axises), of the circle by setting the properties X, Y, RadiusX and RadiusY. This can be done by using their respective setter methods as shown in the following code block. ellipse.setCenterX(300.0f); ellipse.setCenterY(150.0f); ellipse.setRadiusX(150.0f); ellipse.setRadiusY(75.0f); 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. This class is instantiated by passing the Ellipse (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 shown in the following code block − Group root = new Group(ellipse); 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 an Ellipse using JavaFX. Save this code in a file with the name EllipseExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; public class EllipseExample extends Application { @Override public void start(Stage stage) { //Drawing an ellipse Ellipse ellipse = new Ellipse(); //Setting the properties of the ellipse ellipse.setCenterX(300.0f); ellipse.setCenterY(150.0f); ellipse.setRadiusX(150.0f); ellipse.setRadiusY(75.0f); //Creating a Group object Group root = new Group(ellipse); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing an Ellipse”); //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 EllipseExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls EllipseExample Output On executing, the above program generates a JavaFX window displaying an ellipse as shown below. Example In another example given below, let us try to draw an elliptical orbit of a circular planet. Name this file as PlanetOrbit.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Circle; import javafx.scene.paint.Color; import javafx.animation.PathTransition; import javafx.application.Application; import javafx.stage.Stage; import javafx.util.Duration; public class PlanetOrbit extends Application { @Override public void start(Stage stage) { //Drawing an orbit Ellipse orbit = new Ellipse(); orbit.setFill(Color.WHITE); orbit.setStroke(Color.BLACK); //Setting the properties of the ellipse orbit.setCenterX(300.0f); orbit.setCenterY(150.0f); orbit.setRadiusX(150.0f); orbit.setRadiusY(100.0f); // Drawing a circular planet Circle planet = new Circle(300.0f, 50.0f, 40.0f); //Creating the animation PathTransition pathTransition = new PathTransition(); pathTransition.setDuration(Duration.millis(1000)); pathTransition.setNode(planet); pathTransition.setPath(orbit); pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT); pathTransition.setCycleCount(50); pathTransition.setAutoReverse(false); pathTransition.play(); //Creating a Group object Group root = new Group(); root.getChildren().addAll(orbit, planet); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Planet Orbit”); //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 PlanetOrbit.java java –module-path %PATH_TO_FX% –add-modules javafx.controls PlanetOrbit Output On executing, the above program generates a JavaFX window displaying an orbit as shown below. Print Page Previous Next Advertisements ”;

JavaFX – Stroke Miter Limit Property

JavaFX – Stroke Miter Limit Property ”; Previous Next JavaFX allows a user to create a 2D object using multiple lines, instead of having classes for each 2D shape that exists. There are several shapes that do not fall under the category of conventional 2D shapes. In such cases you can join multiple lines to form an unconventional 2D shape, by applying several properties supported by JavaFX on these line while combining them together. One such property is Stroke Line Join Property. The Stroke Line Join Property is used to set the type of the joint while combining multiple line objects to form another 2D shape. This property is of three types as follows − Bevel − In bevel join, the outside edges of the intersection are connected with a line segment. Miter − In miter join, the outside edges of the intersection are joined together forming a sharp edge. Round − In round join, the outside edges of the intersection are joined by rounding off the corner, the radius of this will be exactly half the width of the join. By default, the Stroke Line Joining a shape is miter. However, this miter join also has additional properties to make the join better. This property is known as Stroke Miter Limit Property. Stroke Miter Limit Property This property is of the type double. It represents the limit for the distance between the inside point of the joint and the outside point of the joint. If the distance between these two points exceeds the given limit, the miter is cut at the edge. You can set value to this property using the method setStroke() as follows − path.setStrokeMiterLimit(4); By default, the stroke miter limit value id 10 of the stroke is black. Following is a diagram of a triangle with different stroke limits. Example Let us see an example demonstrating the usage of Stroke Line Join property on a triangle. Save this file with the name StrokeMiterLimitExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.scene.shape.StrokeLineJoin; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeMiterLimitExample extends Application { @Override public void start(Stage stage) { //Creating a Triangle Polygon triangle = new Polygon(); //Adding coordinates to the polygon triangle.getPoints().addAll(new Double[]{ 100.0, 50.0, 170.0, 150.0, 100.0, 250.0, }); triangle.setFill(Color.BLUE); triangle.setStroke(Color.BLACK); triangle.setStrokeWidth(7.0); triangle.setStrokeMiterLimit(4.0); //Creating a Group object Group root = new Group(triangle); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Triangle”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 StrokeMiterLimitExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeMiterLimitExample Output On executing, the above program generates a JavaFX window displaying a triangle with stroke line join of miter limit 4 as shown below. Example Let us see an example demonstrating the usage of Stroke Miter Limit property on a polygon. In here, we will try to pass a value that is relatively higher than the default miter limit. Save this file with the name StrokeMiterLimitPolygon.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.scene.shape.StrokeLineJoin; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeMiterLimitPolygon 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, 170.0, 50.0, 170.0, 150.0, 100.0, 150.0, 135.0, 200.0, }); polygon.setFill(Color.ORANGE); polygon.setStroke(Color.BLACK); polygon.setStrokeWidth(5.0); polygon.setStrokeLineJoin(StrokeLineJoin.MITER); polygon.setStrokeMiterLimit(1000.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 StrokeMiterLimitPolygon.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeMiterLimitPolygon Output On executing, the above program generates a JavaFX window displaying a triangle with stroke line join of miter limit 4 as shown below. Print Page Previous Next Advertisements ”;

JavaFX – ScrollPane

JavaFX – ScrollPane ”; Previous Next ScrollPane is a control that provides a scrollable viewport of its contents. It allows the user to scroll the content vertically or horizontally by using scroll bars. It is used to display a component that is large or one whose size can change dynamically when the screen viewport is limited. Remember, the size of the scroll bars depends on the size of the component. The below figure shows a scrollable viewport with vertical scroll bars − ScrollPane in JavaFX In JavaFX, the scrollpane control is represented by a class named ScrollPane. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a ScrollPane control in JavaFX. This class has the following constructors − ScrollPane() − It constructs a ScrollPane without any node. ScrollPane(Node content) − It constructs a new ScrollPane with the specified node. Steps to create a ScrollPane in JavaFX To create a ScrollPane in JavaFX, follow the steps given below. Step 1: Create a node to display within the ScrollPane In JavaFX, the scrollpane can display nodes that can contain an image, a text or a chart. Hence, instantiate the respected class to create the desired node. Here, we are using an image as a content for the ScrollPane − // create an image view ImageView imageTp = new ImageView(new Image(“tutorials_point.jpg”)); Step 2: Instantiate the ScrollPane class Instantiate the class named ScrollPane inside the start() method. This action will create a ScrollPane for the ImageView. // create a scroll pane ScrollPane newscroll = new ScrollPane(); Step 3: Set the Content of the ScrollPane To set the content of the ScrollPane, we use the method named setContent(). Pass the ImageView object to this method as a parameter value. // set the content of the scroll pane newscroll.setContent(imageTp); Step 4: Launch the Application Once the ScrollPane is created and its content is set, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the ScrollPane object as a parameter value to its constructor along with the dimensions of the application screen. Then, set the title of 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 create a ScrollPane within JavaFX application. Save this code in a file with the name JavafxScrollpane.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class JavafxScrollpane extends Application { @Override public void start(Stage stage) { // creating an image view ImageView imageTp = new ImageView(new Image(“tutorials_point.jpg”)); // creating a scroll pane ScrollPane newscroll = new ScrollPane(); // setting the content of the scroll pane newscroll.setContent(imageTp); // creating a scene and stage Scene scene = new Scene(newscroll, 500, 300); stage.setTitle(“ScrollPane 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 JavafxScrollpane.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxScrollpane Output When we execute the above code, it will generate the following output. Disable Vertical Scroll bar of ScrollPane in JavaFX The ScrollPane class provides two methods namely setHbarPolicy() and setVbarPolicy() to specify when to use the scroll bars. To enable the scroll bar, we pass the ScrollBarPolicy.ALWAYS property to the respective methods and to disable, we use ScrollBarPolicy.NEVER property. Example In the following example, we are going to disable the vertical scroll bar of the ScrollPane. Save this code in a file with the name JavafxScrollpane.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.ScrollPane; import javafx.scene.control.ScrollPane.*; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class JavafxScrollpane extends Application { @Override public void start(Stage stage) { // creating an image view ImageView imageTp = new ImageView(new Image(“tutorials_point.jpg”)); // creating a scroll pane ScrollPane newscroll = new ScrollPane(); // disbaling the vertical scroll bar newscroll.setHbarPolicy(ScrollBarPolicy.ALWAYS); newscroll.setVbarPolicy(ScrollBarPolicy.NEVER); // setting the content of the scroll pane newscroll.setContent(imageTp); // creating a scene and stage Scene scene = new Scene(newscroll, 500, 300); stage.setTitle(“ScrollPane 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 by using the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxScrollpane.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxScrollpane Output On executing the above code, it will generate the following output. Print Page Previous Next Advertisements ”;

JavaFX – Shearing Transformation

JavaFX – Shearing Transformation ”; Previous Next A transformation that slants the shape of an object is called the Shear Transformation. There are two shear transformations X-Shear and Y-Shear. One shifts the X coordinate values and the other shifts the Y coordinate values. However, in both the cases only one coordinate changes its coordinates and the other preserves its values. Shearing is also termed as Skewing. Example 1 Following is the program which demonstrates shearing in JavaFX. Here, we are creating 2 polygons (nodes) at the same location, with the same dimensions, but with different colors (Blue and Transparent). We are also applying shearing on the transparent polygon. Save this code in a file with the name XShearingExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.scene.transform.Shear; import javafx.stage.Stage; public class XShearingExample extends Application { @Override public void start(Stage stage) { Polygon hexagon1 = new Polygon(); //Adding coordinates to the hexagon hexagon1.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, }); //Setting the fill color for the hexagon hexagon1.setFill(Color.BLUE); hexagon1.setStroke(Color.BLACK); Polygon hexagon2 = new Polygon(); //Adding coordinates to the hexagon hexagon2.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, }); //Setting the fill color for the hexagon hexagon2.setFill(Color.TRANSPARENT); hexagon2.setStroke(Color.BLACK); //Creating shear transformation Shear shear = new Shear(); //Setting the pivot points shear.setPivotX(200); shear.setPivotY(250); //Setting the dimensions for the shear shear.setX(0.5); shear.setY(0.0); //Adding the transformation to the polygon hexagon2.getTransforms().addAll(shear); //Creating a Group object Group root = new Group(hexagon1, hexagon2); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Shearing 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 XShearingExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls XShearingExample Output On executing, the above program generates a JavaFX window as shown below. Example 2 In the previous example, we have seen how to perform X-Shear by skewing the hexagon with respect to the X-axis. In this example, let us see Y-Shear performed on another JavaFX 2D shape, say pentagon. Save this code in a file with the name YShearingExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Polygon; import javafx.scene.transform.Shear; import javafx.stage.Stage; public class YShearingExample extends Application { @Override public void start(Stage stage) { Polygon pentagon1 = new Polygon(); //Adding coordinates to the pentagon pentagon1.getPoints().addAll(new Double[]{ 200.0, 50.0, 400.0, 50.0, 450.0, 150.0, 400.0, 250.0, 200.0, 250.0, }); //Setting the fill color for the pentagon pentagon1.setFill(Color.ORANGE); pentagon1.setStroke(Color.BLACK); Polygon pentagon2 = new Polygon(); //Adding coordinates to the pentagon pentagon2.getPoints().addAll(new Double[]{ 200.0, 50.0, 400.0, 50.0, 450.0, 150.0, 400.0, 250.0, 200.0, 250.0, }); //Setting the fill color for the pentagon pentagon2.setFill(Color.TRANSPARENT); pentagon2.setStroke(Color.BLACK); //Creating shear transformation Shear shear = new Shear(); //Setting the pivot points shear.setPivotX(200); shear.setPivotY(250); //Setting the dimensions for the shear shear.setX(0.0); shear.setY(0.5); //Adding the transformation to the polygon pentagon2.getTransforms().addAll(shear); //Creating a Group object Group root = new Group(pentagon1, pentagon2); //Creating a scene object Scene scene = new Scene(root, 600, 400); //Setting title to the Stage stage.setTitle(“Shearing 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 YShearingExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls YShearingExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;