JavaFX – FileChooser ”; Previous Next A file chooser is a graphical user interface elements that allow users to browse through file system. Generally, it is used to open and save either single or multiple files. In the below figure, we can see a file chooser in google drive application − FileChooser in JavaFX In JavaFX, the file chooser is represented by a class named FileChooser which belongs to a package named javafx.scene.control. We can create a file chooser component within our JavaFX application by instantiating this class. This class has only one constructor, i.e. its default constructor. However, it provides multiple properties, which are listed below − initialDirectory − This property specifies the initial directory of the file chooser. You can set value to it using the setInitialDirectory() method. selectedExtensionFilter − This property specifies the extension filter displayed in the dialog. You can set value to it using the setSelectedExtensionFilter() method. Title − The property specifies the title of the dialog. can set value to it using the setTitle() method. How to create a FileChooser in JavaFX? Follow the steps given below to create a file chooser in JavaFX. Step 1: Create a node to associate the FileChooser A file chooser must be associated with another node, like menu or button, so that when the node is clicked, a dialog window opens for file selection. For this purpose, we have used a Menu as shown in the below code − //Creating a menu Menu fileMenu = new Menu(“File”); //Creating menu Items MenuItem item = new MenuItem(“Open Image”); Step 2: Instantiate the FileChooser class To create a file chooser, instantiate the FileChooser class. Then, set the desired file extension with the help of getExtensionFilters() method as shown in the following code block − //Creating a File chooser FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(“Open Image”); fileChooser.getExtensionFilters().addAll(new ExtensionFilter(“All Files”, “*.*”)); Step 3: Add action handler to the Menu It is important to set an action to the menu as it will trigger the opening of the file chooser dialog. //Adding action on the menu item item.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { //Opening a dialog box fileChooser.showOpenDialog(stage); }}); Step 4: Launch the Application Once the file chooser is created and its properties are set, create a MenuBar. Next, pass the Menubar object to the constructor of Group class. Then, set the Scene and Stage. Lastly, launch the application with the help of the launch() method. Example Following is the program that will create a FileChooser using JavaFX. Save this code in a file with the name JavafxFilechooser.java. import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; 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.scene.paint.Color; import javafx.stage.FileChooser; import javafx.stage.Stage; import javafx.stage.FileChooser.ExtensionFilter; public class JavafxFilechooser extends Application { public void start(Stage stage) { //Creating a menu Menu fileMenu = new Menu(“File”); //Creating menu Items MenuItem item = new MenuItem(“Open Image”); fileMenu.getItems().addAll(item); //Creating a File chooser FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(“Open Image”); fileChooser.getExtensionFilters().addAll(new ExtensionFilter(“All Files”, “*.*”)); //Adding action on the menu item item.setOnAction(new EventHandler<ActionEvent>() { public void handle(ActionEvent event) { //Opening a dialog box fileChooser.showOpenDialog(stage); }}); //Creating a menu bar and adding menu to it. MenuBar menuBar = new MenuBar(fileMenu); menuBar.setTranslateX(3); menuBar.setTranslateY(3); //Setting the stage Group root = new Group(menuBar); Scene scene = new Scene(root, 400, 300, Color.BEIGE); stage.setTitle(“File Chooser Example”); 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 JavafxFilechooser.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxFilechooser Output On executing, the above program displays a Button. When we click that button, it will show a pop-up window allowing the user to choose a file. Print Page Previous Next Advertisements ”;
Category: javafx
JavaFX – CheckBox
JavaFX – CheckBox ”; Previous Next Checkbox is a user interface component that allows the user to select or deselect an option. It is most commonly used to create multiple-choice questions, preferences, filters, and many more. The figure below shows a filter feature with multiple options, allowing users to choose a category and brand according to their preferences. Creating CheckBox in JavaFX In JavaFX, the checkbox is represented by a class named CheckBox. This class belongs to the javafx.scene.control package. By instantiating this class, we can create a checkbox in JavaFX. Constructors of the CheckBox class are listed below − CheckBox() − It is the default constructor that constructs a CheckBox without any option name. CheckBox(String str) − It constructs a new CheckBox with the specified option. The most commonly used constructor of the CheckBox class is its parameterized constructor. It accepts a text representing the option name of the CheckBox. Once the checkbox is created, define a layout pane, such as Vbox or Hbox by passing the CheckBox object to its constructor. Then, create a Scene and pass the object of layout pane as a parameter value to its constructor. Next, set the stage and title of the JavaFX application. Finally, call the main() method to launch the application. Example Following is the program that will create the CheckBox using JavaFX. Save this code in a file with the name CheckBoxDemo.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.geometry.Pos; import javafx.geometry.Insets; public class CheckBoxDemo extends Application { @Override public void start(Stage stage) throws Exception { // Creating a Label Label label = new Label(“Click the box to select: “); // Creating three CheckBoxes CheckBox checkBx1 = new CheckBox(“Item1”); checkBx1.setTextFill(Color.GREEN); checkBx1.setSelected(false); CheckBox checkBx2 = new CheckBox(“Item2”); checkBx2.setTextFill(Color.BLUE); checkBx2.setSelected(false); CheckBox checkBx3 = new CheckBox(“Item3”); checkBx3.setTextFill(Color.SKYBLUE); checkBx3.setSelected(false); // Create a Label to display the selection Label selectLabel = new Label(); selectLabel.setTextFill(Color.RED); // Adding listeners to the CheckBoxes checkBx1.setOnAction(e -> selectLabel.setText(“You selected: ” + (checkBx1.isSelected() ? “Item1” : “”) )); checkBx2.setOnAction(e -> selectLabel.setText(“You selected: ” + (checkBx2.isSelected() ? “Item2” : “”) )); checkBx3.setOnAction(e -> selectLabel.setText(“You selected: ” + (checkBx2.isSelected() ? “Item3” : “”) )); // Create a VBox and add the CheckBoxes and Label VBox vbox = new VBox(); vbox.setAlignment(Pos.CENTER); vbox.setPadding(new Insets(10)); vbox.setSpacing(10); vbox.getChildren().addAll(label, checkBx1, checkBx2, checkBx3, selectLabel); // Create a scene and add the VBox Scene scene = new Scene(vbox, 400, 300); // Set the scene and show the stage stage.setScene(scene); stage.setTitle(“CheckBox 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 CheckBoxDemo.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CheckBoxDemo Output On executing, the above program generates a JavaFX window displaying three checkboxes as shown below − Creating CheckBox using default constructor in JavaFX As we discussed earlier, we can create CheckBox in JavaFX either by using its default constructor or its parameterized constructor. In the next example, we will use the default constructor and pass the option text with the help of a built-in method named setText(). Save this code in a file with the name JavafxCheckbox.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.Label; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.geometry.Pos; import javafx.geometry.Insets; public class JavafxCheckbox extends Application { @Override public void start(Stage stage) throws Exception { // Creating a Label Label label = new Label(“Click the box to select: “); // Creating three CheckBoxes without label text CheckBox checkBx1 = new CheckBox(); checkBx1.setTextFill(Color.GREEN); checkBx1.setSelected(true); // adding lable to the check box1 checkBx1.setText(“Item1”); CheckBox checkBx2 = new CheckBox(); // adding lable to the check box2 checkBx2.setText(“Item2”); checkBx2.setTextFill(Color.BLUE); checkBx2.setSelected(false); // Create a Label to display the selection Label selectLabel = new Label(); selectLabel.setTextFill(Color.RED); // Adding listeners to the CheckBoxes checkBx1.setOnAction(e -> selectLabel.setText(“You selected: ” + (checkBx1.isSelected() ? “Item1” : “”) )); checkBx2.setOnAction(e -> selectLabel.setText(“You selected: ” + (checkBx2.isSelected() ? “Item2” : “”) )); // Create a HBox and add the CheckBoxes and Label HBox box = new HBox(); box.setAlignment(Pos.CENTER); box.setPadding(new Insets(10)); box.setSpacing(10); box.getChildren().addAll(label, checkBx1, checkBx2, selectLabel); // Create a scene and add the HBox Scene scene = new Scene(box, 400, 300); // Set the scene and show the stage stage.setScene(scene); stage.setTitle(“CheckBox 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 JavafxCheckbox.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxCheckbox Output On executing the above program, it will generate a JavaFX window displaying two checkboxes as shown below − Print Page Previous Next Advertisements ”;
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 ”; 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 ”; 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 – Parallel Transition
JavaFX – Parallel Transition ”; Previous Next As we learned previously, JavaFX allows you to apply multiple transitions on a node. This can be done by applying one transition at a time (called sequential transitions) or applying multiple transitions at a time (called parallel transitions). Parallel transitions, like its name suggests, applies more than one transition on a single object at one parallelly. For instance, the JavaFX node on which these transitions are applied, can grow in size while moving from one place to another. This can be achieved by applying Scale and Translate transitions together. Let us learn more about parallel transitions elaborately in this chapter. Parallel Transition ParallelTransition class is used to play multiple transitions parallelly on a JavaFX node. This class belongs to the javafx.animation package. All the transitions applied on the node are child transitions of this class that inherit its node property; if their node property is not specified. Example Following is the program which demonstrates Parallel Transition in JavaFX. Save this code in a file with the name parallelTransitionExample.java. import javafx.animation.ParallelTransition; import javafx.animation.PathTransition; import javafx.animation.ScaleTransition; import javafx.animation.TranslateTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; import javafx.util.Duration; public class parallelTransitionExample extends Application { @Override public void start(Stage stage) { //Drawing a Rectangle Rectangle rectangle = new Rectangle(); //Setting the position of the rectangle rectangle.setX(75.0f); rectangle.setY(75.0f); //Setting the width of the rectangle rectangle.setWidth(100.0f); //Setting the height of the rectangle rectangle.setHeight(100.0f); //setting the color of the rectangle rectangle.setFill(Color.BLUEVIOLET); //Instantiating the path class Path path = new Path(); //Creating the MoveTo path element MoveTo moveTo = new MoveTo(100, 150); //Creating the Cubic curve path element CubicCurveTo cubicCurveTo = new CubicCurveTo(400, 40, 175, 250, 500, 150); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(cubicCurveTo); //Creating Path Transition PathTransition pathTransition = new PathTransition(); //Setting the duration of the transition pathTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition pathTransition.setNode(rectangle); //Setting the path for the transition pathTransition.setPath(path); //Setting the orientation of the path pathTransition.setOrientation( PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT); //Setting the cycle count for the transition pathTransition.setCycleCount(5); //Setting auto reverse value to false pathTransition.setAutoReverse(false); //Playing the animation pathTransition.play(); //Creating Translate Transition TranslateTransition translateTransition = new TranslateTransition(); //Setting the duration for the transition translateTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition translateTransition.setNode(rectangle); //Setting the axis and length of the transition translateTransition.setByX(300); //Setting the cycle count of the transition translateTransition.setCycleCount(5); //Setting auto reverse value to false translateTransition.setAutoReverse(false); //Creating scale Transition ScaleTransition scaleTransition = new ScaleTransition(); //Setting the duration for the transition translateTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition translateTransition.setNode(rectangle); //Setting the dimensions for scaling scaleTransition.setByY(1.5); scaleTransition.setByX(1.5); //Setting the cycle count for the translation scaleTransition.setCycleCount(5); //Setting auto reverse value to true scaleTransition.setAutoReverse(false); //Applying parallel Translation to the circle ParallelTransition parallelTransition = new ParallelTransition( rectangle, pathTransition, translateTransition, scaleTransition ); //Playing the animation parallelTransition.play(); //Creating a Group object Group root = new Group(rectangle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Parallel Transition example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls parallelTransitionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls parallelTransitionExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – CubicCurveTo Path Object ”; Previous Next A Cubic curve is a two dimensional structure that is a type of a Bezier curve. A Bezier curve is defined as a curve that passes through a set of control points (P0…Pn). It is called a Cubic curve when the number of control points are 4 (or, if the order of the curve is 3). JavaFX also provides a CubicCurve Path object to draw a more complex shape. Here, we will be considering only the end points of the Cubic Curve and the control points in order to construct a Path object. Let us see how to construct it in detail further. CubicCurve Path Object The path element cubic curve is used to draw a cubic curve to a point in the specified coordinates from the current position. It is represented by a class named CubicCurveTo. This class belongs to the package javafx.scene.shape. This class has 6 properties of the double datatype namely − setX − The x coordinate of the point to which a curve is to be drawn from the current position. setX − The y coordinate of the point to which a curve is to be drawn from the current position. controlX1 − The x coordinate of the 1st control point of the curve. controlY1 − The y coordinate of the 1st control point of the curve. controlX2 − The x coordinate of the 2nd control point of the curve. controlY2 − The y coordinate of the 2nd control point of the curve. To draw a cubic curve, you need to pass values to these properties. This can be done by passing them to the constructor of this class. These should be in the same order as they were at the time of instantiation; Or, by using their respective setter methods. Steps to draw PathElement Cubic Curve To draw a cubic curve to a specified point from the current position in JavaFX, follow the steps given below. Step 1: Creating a Class Create a Cubic Curve Path object inside the start() method of the Application class as shown below. 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 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 CubicCurveTo Create the path element quadratic curve by instantiating the class named CubicCurveTo, which belongs to the package javafx.scene.shape as shown below − //Creating an object of the class CubicCurveTo CubicCurveTo cubicCurveTo= new CubicCurveTo (); Step 4: Setting Properties to the Cubic Curve Element Specify the coordinates of the point to which a cubic curve is to be drawn from the current position. Then you should set the properties x, y, controlX1, controlY1, controlX2, controlY2 and the coordinates of the control point by their setter methods as shown below. //Setting properties of the class CubicCurve cubicCurveTo.setControlX1(400.0f); cubicCurveTo.setControlY1(40.0f); cubicCurveTo.setControlX2(175.0f); cubicCurveTo.setControlY2(250.0f); cubicCurveTo.setX(500.0f); cubicCurveTo.setY(150.0f); Step 5: Adding Elements to the Observable List of Path Class Add the path elements → MoveTo and CubicCurveTo, created in the previous steps to the observable list of the Path class as follows − //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(cubicCurveTo); Step 6: Launching Application Once the CubicCurveTo path object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is the program which draws a cubic curve from the current point to a specified position using the class named Path of JavaFX. Save this code in a file with the name CubicCurveToExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.CubicCurveTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class CubicCurveToExample 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 CubicCurve CubicCurveTo cubicCurveTo = new CubicCurveTo(); //Setting properties of the class CubicCurve cubicCurveTo.setControlX1(400.0f); cubicCurveTo.setControlY1(40.0f); cubicCurveTo.setControlX2(175.0f); cubicCurveTo.setControlY2(250.0f); cubicCurveTo.setX(500.0f); cubicCurveTo.setY(150.0f); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(cubicCurveTo); //Creating a Group object Group root = new Group(path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a cubic through a specified path”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } 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 CubicCurveToExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CubicCurveToExample Output On executing, the above program generates a JavaFX window displaying a Cubic curve. This is drawn from the current position to the specified point as shown below. Example In another example, we are trying to apply Stroke Transition Animation on Cubic Curve Path. Here, the stroke of said 2D shape is set to change its color from BLACK to BROWN. Save this code in a file with the name CubicCurveToAnimation.java. import javafx.application.Application; import javafx.animation.StrokeTransition; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.CubicCurveTo; import javafx.util.Duration; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.scene.paint.Color; public class CubicCurveToAnimation extends
JavaFX – Separator
JavaFX – Separator ”; Previous Next A separator is a horizontal or vertical line that serves to divide UI elements of the JavaFX application. Note that it does not produce any action. However, it is possible to style it, apply visual effects to it, or even animate it to provide a better user experience. In the below figure, we can see a vertical and a horizontal separator − Separator in JavaFX In JavaFX, the separator is represented by a class named Separator. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a separator in JavaFX. This class has the following constructors − Separator() − It creates a new horizontal separator. Separator(Orientation orientation) − It creates a separator with the specified orientation. The orientation could be either vertical or horizontal. Creating a Separator in JavaFX We need to follow the steps given below to create a Separator in JavaFX. Step 1: Create nodes that are going to be separated Since separators are used to separate UI nodes in JavaFX. Hence, it is required to specify the UI elements that are going to be separated. For instance, we are creating Buttons using the below code − // Creating Buttons Button btn1 = new Button(“Button 1”); Button btn2 = new Button(“Button 2”); Button btn3 = new Button(“Button 3”); Button btn4 = new Button(“Button 4”); Step 2: Instantiate the Separator class In JavaFX, the separators are created by instantiating the class named Separators which belongs to a package javafx.scene.control. Instantiate this class inside the start() method as shown below − // creating a separator Separator sep1 = new Separator(); Step 3: Set the desired Orientation By default, the separator is horizontal, but, we can change its orientation by using the setOrientation() method and passing an Orientation enum value (HORIZONTAL or VERTICAL) as an argument. The code shown below will set the orientation to vertical − sep1.setOrientation(Orientation.VERTICAL); Also, the Separator occupies the full horizontal or vertical space allocated to it. Hence, it is necessary to set its maximum width or height as per the requirement by using the setMaxWidth() or setMaxHeight methods. To specify the horizontal or vertical alignment of the separator line within the allocated space, use the setHalignment or setValignment methods and pass an HPos or VPos enum value as an argument. Step 4: Launch the Application Once the Separator is created, 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 create a separator between buttons in JavaFX application. Save this code in a file with the name JavafxSeparator.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.layout.GridPane; import javafx.geometry.Orientation; import javafx.stage.Stage; import javafx.geometry.Pos; public class JavafxSeparator extends Application { @Override public void start(Stage stage) { // creating grid to contain buttons GridPane newgrid = new GridPane(); // set horizontal and vertical gap newgrid.setHgap(10); newgrid.setVgap(10); newgrid.setAlignment(Pos.CENTER); // Creating Buttons Button btn1 = new Button(“Button 1”); Button btn2 = new Button(“Button 2”); Button btn3 = new Button(“Button 3”); Button btn4 = new Button(“Button 4”); // adding buttons to the grid newgrid.add(btn1, 0, 0); newgrid.add(btn2, 2, 0); newgrid.add(btn3, 0, 1); newgrid.add(btn4, 2, 1); // creating a horizontal and a vertical separator Separator sep1 = new Separator(); Separator sep2 = new Separator(); sep2.setOrientation(Orientation.VERTICAL); // Setting background color to the separators sep1.setStyle(“-fx-background-color: #D2691E;”); sep2.setStyle(“-fx-background-color: #D2691E;”); // adding separators to the grid newgrid.add(sep1, 0, 2, 2, 1); newgrid.add(sep2, 1, 0, 1, 2); // creating scene and stage Scene scene = new Scene(newgrid, 400, 300); stage.setTitle(“Separator 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 JavafxSeparator.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxSeparator Output When we execute the above code, it will generate the following output. Creating a Separator in JavaFX using its parameterized constructor As previously discussed, there are two ways to create a separator in JavaFX: one utilizes the default constructor of the Separator class, while the other uses its parameterized constructor. In the next example, we are going to use the parameterized constructor of the Separator class to create a separator in JavaFX. Save this code in a file with the name VerticalSeparator.java. Example import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Separator; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.stage.Stage; import javafx.geometry.Orientation; public class VerticalSeparator extends Application { @Override public void start(Stage stage) { // creating three text fields TextField textField1 = new TextField(); TextField textField2 = new TextField(); TextField textField3 = new TextField(); // creating vertical separators Separator separator1 = new Separator(Orientation.VERTICAL); Separator separator2 = new Separator(Orientation.VERTICAL); // creating HBox HBox hbox = new HBox(); hbox.setPadding(new Insets(15, 12, 15, 12)); hbox.setSpacing(10); hbox.getChildren().addAll(textField1, separator1, textField2, separator2, textField3); // setting the scene and stage Scene scene = new Scene(hbox, 500, 300); 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 VerticalSeparator.java java
JavaFX – TabPane
JavaFX – TabPane ”; Previous Next A TabPane serves as a container for one or more Tab objects. The term tab refers to a section at the top of display area that represents another web page or content. The content of a web page becomes visible only when its corresponding tab is clicked. We can see three tabs are open in the below figure − TabPane in JavaFX In JavaFX, the class named TabPane represents a tabpane. To use the feature of tabpane, we need to create an instance of the TabPane class and add the tabs we want to display inside it. These tabs can contain any JavaFX nodes as the content of a tab, such as labels, buttons, images, text fields, videos and so on. We can use any of the below constructors to create a tabpane − TabPane() − It is used to create an empty tabpane. TabPane(Tab tabs) − It is the parameterized constructor of TabPane class which will create a new tabpane with the specified set of tabs. Steps to create a TabPane in JavaFX To create a TabPane in JavaFX, follow the steps given below. Step 1: Create desired number of Tabs As discussed earlier, a tabpane contains one or more Tabs. Therefore, our first step would be creating tabs to display within the tabpane. Here, we are going to create three tabs namely Label, Image and Video. In JavaFX, the tabs are created by instantiating the class named Tab which belongs to a package javafx.scene.control. A Tab object has a text property that sets the title of the tab. Create the tabs using the following code − // Creating a Label tab Tab tab1 = new Tab(“Label”); // Creating an Image tab Tab tab2 = new Tab(“Image”); // Creating a Video tab Tab tab3 = new Tab(“Video”); Step 2: Set the content of Tabs The Tab object has a content property that sets the node to be displayed in the tab body. For this action, we use the setContent() method. It is used along with the Tab object and accepts Node object as an argument to its constructor as shown in the below code − // setting the Label tab tab1.setContent(new Label(“This is the first tab”)); // setting the Image tab tab2.setContent(imageView); // setting the Video tab tab3.setContent(vbox); Step 3: Instantiate the TabPane class To create the tabpane, instantiate the TabPane class of package javafx.scene.control without passing any parameter value to its constructor and add all the tabs to the tabpane using the getTabs() method. // Creating a TabPane TabPane tabPane = new TabPane(); // Adding all the tabs to the TabPane tabPane.getTabs().addAll(tab1, tab2, tab3); Step 4: Launching Application After creating the TabPane and adding the tabs to it, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the TabPane object as a parameter value to its constructor. Also, pass the 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 In the following example, we are going to create a TabPane in JavaFX application. Save this code in a file with the name JavafxtabsDemo.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Tab; import javafx.scene.control.TabPane; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.media.Media; import javafx.scene.media.MediaPlayer; import javafx.scene.media.MediaView; import javafx.stage.Stage; import java.io.File; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.scene.control.Button; import javafx.geometry.Pos; public class JavafxtabsDemo extends Application { @Override public void start(Stage stage) { // Creating a Label tab Tab tab1 = new Tab(“Label”); tab1.setContent(new Label(“This is the first tab”)); // Creating an Image tab Tab tab2 = new Tab(“Image”); Image image = new Image(“tutorials_point.jpg”); ImageView imageView = new ImageView(image); tab2.setContent(imageView); // Creating a Video tab Tab tab3 = new Tab(“Video”); // Passing the video file to the File object File videofile = new File(“sampleTP.mp4”); // creating a Media object from the File Object Media videomedia = new Media(videofile.toURI().toString()); // creating a MediaPlayer object from the Media Object MediaPlayer mdplayer = new MediaPlayer(videomedia); // creating a MediaView object from the MediaPlayer Object MediaView viewmedia = new MediaView(mdplayer); //setting the fit height and width of the media view viewmedia.setFitHeight(350); viewmedia.setFitWidth(350); // creating video controls using the buttons Button pause = new Button(“Pause”); Button resume = new Button(“Resume”); // creating an HBox HBox box = new HBox(20); box.setAlignment(Pos.CENTER); box.getChildren().addAll(pause, resume); // function to handle play and pause buttons pause.setOnAction(act -> mdplayer.pause()); resume.setOnAction(act -> mdplayer.play()); // creating the root VBox vbox = new VBox(20); vbox.setAlignment(Pos.CENTER); vbox.getChildren().addAll(viewmedia, box); tab3.setContent(vbox); // Creating a TabPane TabPane tabPane = new TabPane(); // Adding all the tabs to the TabPane tabPane.getTabs().addAll(tab1, tab2, tab3); // Create a Scene with the TabPane as its root Scene scene = new Scene(tabPane, 400, 400); // Set the Title on the Stage stage.setTitle(“TabPane in JavaFX”); // Set the Scene on the Stage 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,javafx.media JavafxtabsDemo.java java –module-path %PATH_TO_FX% –add-modules javafx.controls,javafx.media JavafxtabsDemo Output When we execute the above code, it will generate a TabPane with three tabs namely Label, Image and Video. Print Page Previous Next Advertisements ”;