JavaFX – PasswordField ”; Previous Next The text field accepts and displays the text. Using this we can accept input from the user and read it to our application. Similar to the text field, a password field accepts text but instead of displaying the given text, it hides the typed characters by displaying an echo string as shown in the below figure − PasswordField in JavaFX In JavaFX, the class named PasswordField represents a password field which is belongs to the javafx.scene.control package. Using this we can accept input from the user and read it to our application. This class inherits the Text class. To create a password field, we need to instantiate this class by using the below constructor − PasswordField() − This is the default constructor which will create an empty password field. While creating a password field in JavaFX, our first step would be instantiating the PasswordField class by using its default constructor. Next, define a layout pane, such as Vbox or Hbox by passing the PasswordField object to its constructor. Lastly, set the scene and stage to display the password field on the screen. Example The following JavaFX program demonstrates how to create a password field in JavaFX application. Save this code in a file with the name JavafxPsswrdfld.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class JavafxPsswrdfld extends Application { public void start(Stage stage) { //Creating nodes TextField textField = new TextField(); PasswordField pwdField = new PasswordField(); //Creating labels Label label1 = new Label(“Name: “); Label label2 = new Label(“Pass word: “); //Adding labels for nodes HBox box = new HBox(5); box.setPadding(new Insets(25, 5 , 5, 50)); box.getChildren().addAll(label1, textField, label2, pwdField); //Setting the stage Scene scene = new Scene(box, 595, 150, Color.BEIGE); stage.setTitle(“Password Field Example”); 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 JavafxPsswrdfld.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxPsswrdfld Output When we execute the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
Category: javafx
JavaFX – ToolBar
JavaFX – ToolBar ”; Previous Next A ToolBar is a graphical user interface control with horizontal or vertical strip of buttons, menus, or other controls. It is often used to provide quick access to frequently used commands or functions. We can locate a toolbar at top of any application or web page as shown in the below figure − ToolBar in JavaFX In JavaFX, the tool bar is represented by the ToolBar class. This class is a part of the package named javafx.scene.control. By instantiating this class, we can create a ToolBar node in JavaFX. It has the following constructors − ToolBar() − It is the default constructor used to create a tool bar without any predefined nodes. ToolBar(Node nodes) − It is the parameterized constructor of ToolBar class which creates a new tool bar with the specified nodes. Steps to create a tool bar in JavaFX Follow the steps given below to create a tool bar in JavaFX. Step 1: Create nodes to display within the ToolBar First, we need to create a list of nodes to display within the ToolBar where, each node represents a distinct command or function. Here, we are going to create buttons, separator and text fields by using the below code blocks − // Creating buttons and a text field Button btnNew = new Button(“New”); Button btnOpen = new Button(“Open”); Button btnSave = new Button(“Save”); Button btnExit = new Button(“Exit”); TextField txtSearch = new TextField(); txtSearch.setPromptText(“Search”); // creating separators Separator sepOne = new Separator(); Separator sepTwo = new Separator(); Step 2: Instantiate the ToolBar class As mentioned earlier, a tool bar is created using the class named ToolBar. Therefore, instantiate this class as shown in the following code block − // creating a toolbar ToolBar toolsB = new ToolBar(); Step 3: Add the nodes to the ToolBar object To add all the nodes to the ToolBar, we use the getItems() and addAll() methods. The code given below demonstrates it− // adding the nodes toolsB.getItems().addAll(btnNew, btnOpen, btnSave, sepOne, txtSearch, sepTwo, btnExit); Step 4: Launching Application Once the tool bar is created and all the nodes are added, follow the given steps below to launch the application properly − Firstly, instantiate the class named BorderPane by passing the ToolBar object as a parameter value to its constructor. However, we can use any of the layout panes such as GridPane or StackPane. Then, instantiate the class named Scene by passing the BorderPane object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is the program that will create a ToolBar using JavaFX. Save this code in a file with the name ToolbarExample.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.control.TextField; import javafx.scene.control.ToolBar; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class ToolbarExample extends Application { @Override public void start(Stage stage) throws Exception { // Creating buttons and a text field Button btnNew = new Button(“New”); Button btnOpen = new Button(“Open”); Button btnSave = new Button(“Save”); Button btnExit = new Button(“Exit”); TextField txtSearch = new TextField(); txtSearch.setPromptText(“Search”); // creating separators Separator sepOne = new Separator(); Separator sepTwo = new Separator(); // creating a toolbar ToolBar toolsB = new ToolBar(); // adding the nodes toolsB.getItems().addAll(btnNew, btnOpen, btnSave, sepOne, txtSearch, sepTwo, btnExit); // Creating a BorderPane as root BorderPane root = new BorderPane(); // adding the ToolBar at the top root.setTop(toolsB); // Create a Scene and set it to the Stage Scene scene = new Scene(root, 400, 300); stage.setTitle(“ToolBar in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls ToolbarExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ToolbarExample Output On executing, the above program generates a JavaFX window displaying a ToolBar with specified buttons and text fields as shown below. Setting the Orientation of the ToolBar To change the orientation of the ToolBar, we can use the setOrientation() method and pass either Orientation.HORIZONTAL or Orientation.VERTICAL as the argument. Example In the following JavaFX program, we will create a vertical ToolBar. Save this code in a file with the name VerticalToolbar.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.Separator; import javafx.scene.control.TextField; import javafx.scene.control.ToolBar; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; import javafx.geometry.Orientation; public class VerticalToolbar extends Application { @Override public void start(Stage stage) throws Exception { // Creating buttons Button btnNew = new Button(“New”); Button btnOpen = new Button(“Open”); Button btnSave = new Button(“Save”); Button btnExit = new Button(“Exit”); // creating separators Separator sepOne = new Separator(); Separator sepTwo = new Separator(); Separator sepThree = new Separator(); // creating a toolbar ToolBar toolsB = new ToolBar(); // adding the nodes toolsB.getItems().addAll(btnNew, sepOne, btnOpen, sepTwo, btnSave, sepThree, btnExit); toolsB.setOrientation(Orientation.VERTICAL); // Creating a BorderPane as root BorderPane root = new BorderPane(); // adding the ToolBar at the top root.setTop(toolsB); // Create a Scene and set it to the Stage Scene scene = new Scene(root, 400, 300); stage.setTitle(“ToolBar in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls VerticalToolbar.java java –module-path %PATH_TO_FX% –add-modules javafx.controls VerticalToolbar Output When we execute the above code, it will generate the following
JavaFX – TableView
JavaFX – TableView ”; Previous Next The TableView is a graphical user interface component used to display data in a tabular form. Similar to a typical table, TableView consists of columns, rows, and cells, each of which can hold any type of data. In general, a table is represented as shown in the following figure − TableView in JavaFX In JavaFX, the table view is represented by the TableView class. This class is a part of the package named javafx.scene.control. By instantiating this class, we can create a TableView node in JavaFX. It has two constructors namely − TableView() − It is the default constructor used to create a table view without any predefined data. TableView(ObservableList items) − It is the parameterized constructor of TableView class which accepts a list of items and creates a new table view with the specified items. Steps to create a TableView in JavaFX Follow the steps given below to create a table view in JavaFX. Step 1: Create a Class to represent Data within the Table First, we need to create a class that represents the data to display within the TableView. This class should have properties that correspond to the columns of the table. Here, we will create a class named movie with properties title, actor, price and rating by using the below code blocks − // The data model class public static class Movie { private final SimpleStringProperty title; private final SimpleStringProperty actor; private final SimpleDoubleProperty price; private final SimpleIntegerProperty rating; Step 2: Create the Columns for the TableView Create TableColumn objects and set their cell value using the setCellValueFactory() method. A cell value factory is a function that tells the column how to extract the data from the above declared data model class. The following code block shows how to create columns − // Creating columns for the TableView TableColumn<Movie, String> titleColumn = new TableColumn<>(“Movie Name”); titleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty()); TableColumn<Movie, String> actorColumn = new TableColumn<>(“Actor”); actorColumn.setCellValueFactory(cellData -> cellData.getValue().authorProperty()); TableColumn<Movie, Number> priceColumn = new TableColumn<>(“Price”); priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty()); TableColumn<Movie, Number> ratingColumn = new TableColumn<>(“IMDB Rating”); ratingColumn.setCellValueFactory(cellData -> cellData.getValue().ratingProperty()); Step 3: Instantiate TableView class Instantiate the TableView class of package javafx.scene.control without passing any parameter value to its constructor and add all the columns using the following code blocks − // Creating a TableView TableView<Movie> tableView = new TableView<>(); // Adding the columns to the TableView tableView.getColumns().addAll(titleColumn, actorColumn, priceColumn, ratingColumn); Step 4: Launching Application Once the table view is created and all the data are added, follow the given steps below to launch the application properly − Firstly, instantiate the class named BorderPane by passing the TableView object as a parameter value to its constructor. Then, instantiate the class named Scene by passing the BorderPane object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is the program that will create a TableView using JavaFX. Save this code in a file with the name JavafxTableview.java. import javafx.application.Application; import javafx.beans.property.SimpleDoubleProperty; import javafx.beans.property.SimpleIntegerProperty; import javafx.beans.property.SimpleStringProperty; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.Scene; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.BorderPane; import javafx.stage.Stage; public class JavafxTableview extends Application { // The data model class public static class Movie { private final SimpleStringProperty title; private final SimpleStringProperty actor; private final SimpleDoubleProperty price; private final SimpleIntegerProperty rating; // constructor public Movie(String title, String actor, double price, int rating) { this.title = new SimpleStringProperty(title); this.actor = new SimpleStringProperty(actor); this.price = new SimpleDoubleProperty(price); this.rating = new SimpleIntegerProperty(rating); } // getters and setters to access the data public SimpleStringProperty titleProperty() { return title; } public SimpleStringProperty authorProperty() { return actor; } public SimpleDoubleProperty priceProperty() { return price; } public SimpleIntegerProperty ratingProperty() { return rating; } } // main method starts here @Override public void start(Stage stage) throws Exception { // adding some sample data ObservableList<Movie> movies = FXCollections.observableArrayList( new Movie(“The Batman”, “Robert Pattinson”, 299, 7), new Movie(“John Wick: Chapter 4”, “Keanu Reeves”, 199, 7), new Movie(“12th Fail”, “Vikrant Massey”, 199, 9), new Movie(“Money Heist”, “Alvaro Morte”, 499, 8), new Movie(“The Family Man”, “Manoj Bajpayee”, 399, 8) ); // Creating a TableView TableView<Movie> tableView = new TableView<>(); // Creating columns for the TableView TableColumn<Movie, String> titleColumn = new TableColumn<>(“Movie Name”); titleColumn.setCellValueFactory(cellData -> cellData.getValue().titleProperty()); TableColumn<Movie, String> actorColumn = new TableColumn<>(“Actor”); actorColumn.setCellValueFactory(cellData -> cellData.getValue().authorProperty()); TableColumn<Movie, Number> priceColumn = new TableColumn<>(“Price”); priceColumn.setCellValueFactory(cellData -> cellData.getValue().priceProperty()); TableColumn<Movie, Number> ratingColumn = new TableColumn<>(“IMDB Rating”); ratingColumn.setCellValueFactory(cellData -> cellData.getValue().ratingProperty()); // Adding the columns to the TableView tableView.getColumns().addAll(titleColumn, actorColumn, priceColumn, ratingColumn); // Set the items of the TableView tableView.setItems(movies); // Create a BorderPane and set the TableView as its center BorderPane root = new BorderPane(); root.setCenter(tableView); // Create a Scene and set it on the Stage Scene scene = new Scene(root, 400, 300); stage.setTitle(“Table View in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxTableview.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxTableview Output On executing, the above program generates a JavaFX window displaying a Tableview with a list of movies as shown below. Creating Nested columns of TableView Sometimes, we are required to display data of a single column in multiple sub-columns. This is common when a single entity has multiple attributes, for instance, a person can have multiple contact numbers or email accounts. In
JavaFX – Cull Face Property
JavaFX – Cull Face Property ”; Previous Next JavaFX also provides various properties for 3D objects. These properties can range from deciding the material of a shape: interior and exterior, rendering the 3D object geometry and culling faces of the 3D shape. All these properties are offered in order to improvise the look and feel of a 3D object; and check what is suitable for the application and apply them. In this chapter, let us learn more about the Cull Face Property. Cull Face Property In general, culling is the removal of improperly oriented parts of a shape (which are not visible in the view area). The Cull Face property is of the type CullFace and it represents the Cull Face of a 3D shape. You can set the Cull Face of a shape using the method setCullFace() as shown below − box.setCullFace(CullFace.NONE); The stroke type of a shape can be − None − No culling is performed (CullFace.NONE). Front − All the front facing polygons are culled. (CullFace.FRONT). Back − All the back facing polygons are culled. (StrokeType.BACK). By default, the cull face of a 3-Dimensional shape is Back. Example The following program is an example which demonstrates various cull faces of the sphere. Save this code in a file with the name SphereCullFace.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.CullFace; import javafx.stage.Stage; import javafx.scene.shape.Sphere; public class SphereCullFace extends Application { @Override public void start(Stage stage) { //Drawing Sphere1 Sphere sphere1 = new Sphere(); //Setting the radius of the Sphere sphere1.setRadius(50.0); //Setting the position of the sphere sphere1.setTranslateX(100); sphere1.setTranslateY(150); //setting the cull face of the sphere to front sphere1.setCullFace(CullFace.FRONT); //Drawing Sphere2 Sphere sphere2 = new Sphere(); //Setting the radius of the Sphere sphere2.setRadius(50.0); //Setting the position of the sphere sphere2.setTranslateX(300); sphere2.setTranslateY(150); //Setting the cull face of the sphere to back sphere2.setCullFace(CullFace.BACK); //Creating a Group object Group root = new Group(sphere1, sphere2); //Creating a scene object Scene scene = new Scene(root, 600, 300); //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 SphereCullFace.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SphereCullFace Output On executing, the above program generates a JavaFX window displaying two spheres with cull face values FRONT and BACK respectively as follows − Example The following program is an example which demonstrates when no cull face property is applied using NONE attribute on a box. Save this code in a file with the name BoxCullFace.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.CullFace; import javafx.stage.Stage; import javafx.scene.shape.Box; public class BoxCullFace extends Application { @Override public void start(Stage stage) { //Drawing Box1 Box box1 = new Box(); //Setting the dimensions of the Box box1.setWidth(100.0); box1.setHeight(100.0); box1.setDepth(100.0); //Setting the position of the box box1.setTranslateX(100); box1.setTranslateY(150); box1.setTranslateZ(0); //setting the cull face of the box to NONE box1.setCullFace(CullFace.NONE); //Creating a Group object Group root = new Group(box1); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Box”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls BoxCullFace.java java –module-path %PATH_TO_FX% –add-modules javafx.controls BoxCullFace Output On executing, the above program generates a JavaFX window displaying a box with cull face values NONE respectively as follows − Print Page Previous Next Advertisements ”;
JavaFX – Handling Media
JavaFX – Handling Media ”; Previous Next In general, media refers to various means of communication such as audio, video, and other forms that can be both one-way or two-way. It is used in the form of music, movies, news, vlogs and so forth. Since media usage became an essential part of our lives, JavaFX creators developed a set of Java APIs that enables the use of media within JavaFX applications. Handling Media in JavaFX To handle media, JavaFX provides javafx.scene.media package that allows developers to embed a media player within the desktop window or a web page on supported platforms for media playback. This package contains the following classes that are used in combination to handle media content − Media − It contains pieces of information like source, resolution, and metadata of a specified media resource. MediaPlayer − It provides the controls for playing media. MediaView − It is a node object used to provide support for animation and other effects to the media resource. The classes mentioned above are not independent, they are always used in the combination to create an embedded media player. All attributes and methods needed to control media playback are made available in MediaPlayer class. More specifically, the play(), stop(), and pause() methods are used to control media playback. To adjust the volume level, we use VOLUME variable. The range of volume level is from 0 to 1.0 (the maximum value). Remember, without the MediaView class, we can”t view the media being played by media player. There are some other additional methods that are used to handle the following events − Buffers data Whenever any errors of the MediaErrorEvent class occur. When media stops because media player has not received data fast enough to continue playing. When the media player reaches the end of media. Supported format of Media in JavaFX The following media formats are supported in JavaFX − S.No Media & Format 1 Audio MP3, AIFF , WAV, and MPEG-4 2 Video FLV containing VP6 video and MP3 audio, and MPEG-4 Features provided by JavaFX media The following features are provided by JavaFX media on devices that support JavaFX − It supports multiple playback functions, such as Play, Pause, Stop, Volume, and Mute. It allows navigation through audio/video in a forward or backward direction as needed. It provides support for HTTP and File protocols. Progressive download It also supports HTTP live streaming. Handling Media Reference Following are the classes and methods that are used for handling media in JavaFX. Media The Media class in the JavaFx is like a container for audio video files. It contains pieces of information like source, resolution, and metadata of a specified media resource. Some of the methods of the ”Media” class listed below are − Sr.No. Methods & Description 1 getDuration() Retrieve the duration in seconds of the media. 2 getWidth() Retrieve the width in pixels of the media. 3 getHeight() Retrieve the height in pixels of the media. 4 getSource() Retrieve the source URI of the media. 5 getError() Return any error encountered in the media. MediaPlayer The MediaPlayer class controls audio and video files and allows for functions like play, pause, and stop, making media control easy. Some of the methods of the ”MediaPlayer” class listed below are − Sr.No. Methods & Description 1 getStatus() Retrieves the current player status. 2 getVolume() Retrieves the audio playback volume. 3 setRate() Sets the playback rate to the supplied value. 4 isAutoPlay() Retrieves the autoPlay property value. 5 getBlance() Retrieves the audio balance. 6 setMute() Sets the value of muteProperty(). 7 getStartTime() Retrieves the start time. 8 getStopTime() Retrieves the stop time. 9 getTotalDuration() Retrieves the total playback duration including all cycles (repetitions). 10 stop() Stops playing the media. MediaView The MediaView class in JavaFX is a special class for displaying videos or media played by a MediaPlayer. Some of the methods of the ”MediaView” class listed below are − Sr.No. Methods & Description 1 getX() Retrieves the x coordinate of the MediaView origin. 2 getY() Retrieves the y coordinate of the MediaView origin. 3 setSmooth() Sets whether to smooth the media when scaling. 4 getViewPort() Retrieves the rectangular viewport into the media frame. 5 isPreserveRatio() Sets whether to preserve the media aspect ratio when scaling. 6 getFitHeight() Retrieves the height of the bounding box of the resized media. 7 getFitWidth() Retrieves the width of the bounding box of the resized media. Print Page Previous Next Advertisements ”;
JavaFX – Slider
JavaFX – Slider ”; Previous Next Slider is a UI control consisting of a track and a thumb along with other optional elements like tick marks and tick labels. It allows the user to select a value from a continuous or discrete range of values by dragging the thumb along a track. The common applications of a slider can be seen in audio or video players, games, brightness controllers and so on. The figure below shows two sliders, one is a volume controller and the other one is a brightness controller. Slider in JavaFX In JavaFX, the slider is represented by a class named Slider. This class belongs to the package javafx.scene.control. By instantiating this class, we can create a slider in JavaFX. Constructors of the Slider class are listed below − Slider() − It is the default constructor. Slider(double minVal, double maxVal, double currentVal) − It creates a new slider with the specified initial, minimum and maximum values. Steps to create a Slider in JavaFX To create a Slider in JavaFX, follow the steps given below. Step 1: Instantiate the Slider class Instantiate the Slider class inside the start() method. This action will create a slider control in JavaFX application. // creating a slider using default constructor Slider slide = new Slider(); Step 2: Set the minimum and maximum values of Slider Every slider comes with minimum and maximum values. To set the minimum value, a built-in method named setMin() is used which accepts a double value as an argument. Similarly, the maximum value is set using the setMax() method, which also requires double as a parameter value. // setting the minimum and maximum values slide.setMin(0); slide.setMax(100); Step 3: Set the Orientation of the Slider To set the orientation of the Slider, we use the method named setOrientation(). It accepts enum values VERTICAL or HORIZONTAL as an argument. // setting the orientation slide.setOrientation(Orientation.VERTICAL); Step 4: Optional Properties of Slider We can also set the various properties of the Slider such as major and minor tick counts, tick marks and labels. To do so, use the following code − // major and minor tick marks slide.setMajorTickUnit(10); slide.setMinorTickCount(9); slide.setShowTickMarks(true); slide.setShowTickLabels(true); Step 5: Launch the Application Once the Slider is created and its properties are set, follow the given steps below to launch the application properly − Firstly, create a VBox that holds the slider. Next, instantiate the class named Scene by passing the VBox 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 In the following example, we are going to create a slider in JavaFX application. Save this code in a file with the name SliderJavafx.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.geometry.Orientation; import javafx.geometry.Pos; public class SliderJavafx extends Application { @Override public void start(Stage stage) { // creating a slider using default constructor Slider slide = new Slider(); // setting the minimum and maximum values slide.setMin(0); slide.setMax(100); // setting the orientation slide.setOrientation(Orientation.VERTICAL); // major and minor tick marks slide.setMajorTickUnit(10); slide.setMinorTickCount(9); slide.setShowTickMarks(true); slide.setShowTickLabels(true); // creating a label to display the slider value Label valueLabel = new Label(“Value: ” + slide.getValue()); // creating a listener to update the label when the slider value changes slide.valueProperty().addListener((observable, oldValue, newValue) -> { valueLabel.setText(“Value: ” + newValue.intValue()); }); // creating a VBox to hold the slider and the label VBox root = new VBox(); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); root.setSpacing(10); root.getChildren().addAll(slide, valueLabel); // create a scene and stage Scene scene = new Scene(root, 400, 300); stage.setTitle(“Slider 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 SliderJavafx.java java –module-path %PATH_TO_FX% –add-modules javafx.controls SliderJavafx Output When we execute the above code, it will generate the following output. Creating a Slider in JavaFX using its parameterized constructor We all know that there are two ways to create a slider in JavaFX: one with the help of default constructor of the Slider class, while the other uses its parameterized constructor. In the next example, we are going to use the parameterized constructor of the Slider class to create a slider in JavaFX. Save this code in a file with the name JavafxSlider.java. Example import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Slider; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.geometry.Orientation; import javafx.geometry.Pos; public class JavafxSlider extends Application { @Override public void start(Stage stage) { // creating a Slider with a range of 0 to 100 Slider slide = new Slider(0, 100, 50); // setting the orientation to horizontal slide.setOrientation(Orientation.HORIZONTAL); // setting the major tick unit to 10 slide.setMajorTickUnit(10); // to show the tick marks and labels slide.setShowTickMarks(true); slide.setShowTickLabels(true); // Label to display the value of the Slider Label label = new Label(“Value: ” + slide.getValue()); // listener to show the value of Slider slide.valueProperty().addListener((observable, oldValue, newValue) -> { // Update the Label with the new value label.setText(“Value: ” + newValue); }); // creating a VBox VBox root = new VBox(10); root.setAlignment(Pos.CENTER); root.setPadding(new Insets(10)); root.getChildren().addAll(slide, label); // creating a Scene and Stage Scene scene = new Scene(root, 400, 300); stage.setTitle(“Slider in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file
JavaFX – Event Handlers
JavaFX – Event Handlers ”; Previous Next Event handlers enable you to handle an event during the event bubbling phase of event processing. The bubbling phase of an event route is a phase where the event travels from target node to stage node. Like Event filters, a node can have one or more handlers, or no handlers at all to handle an event. If the node does not contain a handler, the event reaches the root node and the process is completed. Otherwise, if a node in event dispatch chain contains a handler, the handler is executed. A single handler can be used for more than one node and more than one event type. If an event handler for a child node does not consume the event, an event handler for a parent node enables the parent node to act on the event after a child node processes it and to provide common event processing for multiple child nodes. Adding and Removing Event Handlers To add an event handler to a node, you need to register this handler using the method addEventHandler() of the Node class as shown below. //Creating the mouse event handler EventHandler<javafx.scene.input.MouseEvent> eventHandler = new EventHandler<javafx.scene.input.MouseEvent>() { @Override public void handle(javafx.scene.input.MouseEvent e) { System.out.println(“Hello World”); circle.setFill(Color.DARKSLATEBLUE); } }; //Adding the event handler circle.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandler); In the same way, you can remove an event handler using the method removeEventHandler() as shown below − circle.removeEventHandler(MouseEvent.MOUSE_CLICKED, eventHandler); Example The following program is an example demonstrating the event handling in JavaFX using the event handlers. Save this code in a file with name EventHandlersExample.java. import javafx.animation.RotateTransition; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.PerspectiveCamera; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.Box; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.scene.transform.Rotate; import javafx.stage.Stage; import javafx.util.Duration; public class EventHandlersExample extends Application { @Override public void start(Stage stage) { //Drawing a Box Box box = new Box(); //Setting the properties of the Box box.setWidth(150.0); box.setHeight(150.0); box.setDepth(100.0); //Setting the position of the box box.setTranslateX(350); box.setTranslateY(150); box.setTranslateZ(50); //Setting the text Text text = new Text(“Type any letter to rotate the box, and click on the box to stop the rotation”); //Setting the font of the text text.setFont(Font.font(null, FontWeight.BOLD, 15)); //Setting the color of the text text.setFill(Color.CRIMSON); //setting the position of the text text.setX(20); text.setY(50); //Setting the material of the box PhongMaterial material = new PhongMaterial(); material.setDiffuseColor(Color.DARKSLATEBLUE); //Setting the diffuse color material to box box.setMaterial(material); //Setting the rotation animation to the box RotateTransition rotateTransition = new RotateTransition(); //Setting the duration for the transition rotateTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition rotateTransition.setNode(box); //Setting the axis of the rotation rotateTransition.setAxis(Rotate.Y_AXIS); //Setting the angle of the rotation rotateTransition.setByAngle(360); //Setting the cycle count for the transition rotateTransition.setCycleCount(50); //Setting auto reverse value to false rotateTransition.setAutoReverse(false); //Creating a text filed TextField textField = new TextField(); //Setting the position of the text field textField.setLayoutX(50); textField.setLayoutY(100); //Handling the key typed event EventHandler<KeyEvent> eventHandlerTextField = new EventHandler<KeyEvent>() { @Override public void handle(KeyEvent event) { //Playing the animation rotateTransition.play(); } }; //Adding an event handler to the text feld textField.addEventHandler(KeyEvent.KEY_TYPED, eventHandlerTextField); //Handling the mouse clicked event(on box) EventHandler<javafx.scene.input.MouseEvent> eventHandlerBox = new EventHandler<javafx.scene.input.MouseEvent>() { @Override public void handle(javafx.scene.input.MouseEvent e) { rotateTransition.stop(); } }; //Adding the event handler to the box box.addEventHandler(javafx.scene.input.MouseEvent.MOUSE_CLICKED, eventHandlerBox); //Creating a Group object Group root = new Group(box, textField, text); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting camera PerspectiveCamera camera = new PerspectiveCamera(false); camera.setTranslateX(0); camera.setTranslateY(0); camera.setTranslateZ(0); scene.setCamera(camera); //Setting title to the Stage stage.setTitle(“Event Handlers 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 EventHandlersExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls EventHandlersExample Output On executing, the above program generates a JavaFX window displaying a text field and a 3D box as shown below − Here, if you type a letter in the text field, the 3D box starts rotating along the x axis. If you click on the box again the rotation stops. Example Let us see another scenario where we can use Event Handlers. In this example, we are creating a JavaFX object, say a circle, and applying Fade Transition on it. Using an event handler, we are specifying when the Transition needs to be played and when to be paused; i.e. by clicking on a button. Save this code in a file with name EventHandlersButton.java. import javafx.animation.ScaleTransition; import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.input.MouseEvent; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class EventHandlerButton extends Application{ @Override public void start(Stage primaryStage) throws Exception { // TODO Auto-generated method stub //Creating Circle and setting the color and stroke in the circle Circle c = new Circle(150, 125, 50); c.setFill(Color.RED); c.setStroke(Color.BLACK); //creating play button
JavaFX – Pagination
JavaFX – Pagination ”; Previous Next The Pagination control is a UI component that allows the user to navigate through different pages of content. For example, we can use this feature to display search results, articles, images or any other type of content that requires multiple pages. A typical pagination control has a page navigation area, previous page button and next page button as shown in the figure below − Creating a Pagination in JavaFX In JavaFX, the pagination control is created by instantiating a class named Pagination. This class belongs to the package javafx.scene.control. Constructors of this class are listed below − Pagination() − It will generate a pagination control without page count and the default page index will be zero. However, we can also use this default constructor and set these properties later using the setPageCount() and setCurrentPageIndex() methods. Pagination(int pageCount) − It will create a pagination control with the specified number of pages. Pagination(int pageCount, int currentIndex) − It constructs a new Pagination control with the given number of pages and page index. While creating a pagination in JavaFX, our first step would be instantiating the Pagination class by using any of the above mentioned constructors. Next, define a layout pane, such as Vbox or Hbox by passing the Pagination object to its constructor. Lastly, set the scene and stage to display the pagination control on the screen. Example The following JavaFX program demonstrates how to create a Pagination within JavaFX application. Save this code in a file with the name PaginationJavafx.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Pagination; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.Node; import javafx.util.Callback; import javafx.geometry.Pos; public class PaginationJavafx extends Application { private Pagination paging; @Override public void start(Stage stage) { // instantiating Pagination class paging = new Pagination(5); // to change the page number paging.setPageFactory(new Callback <Integer, Node>() { @Override public Node call(Integer pageIndex) { return new Label(“Page No.” + (pageIndex + 1)); } }); // creating Vbox that will contain the pagination VBox box = new VBox(); box.getChildren().addAll(paging); box.setAlignment(Pos.CENTER); // creating scene and stage Scene scene = new Scene(box, 400, 300); stage.setScene(scene); stage.setTitle(“Pagination in JavaFX”); stage.show(); } // to launch the application 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 PaginationJavafx.java java –module-path %PATH_TO_FX% –add-modules javafx.controls PaginationJavafx Output When we execute the above code, it will generate the following output. Defining Current Index Page One of the constructor of Pagination class accepts two parameters namely page count and current index. Whenever we use this contructor, it will generate a pagination control with the specified number of pages and the currently selected index number. Example In the following example, we are creating a pagination control with currently selected index number as 3. Save this code in a file with the name JavafxPagination.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Pagination; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.Node; import javafx.util.Callback; import javafx.geometry.Pos; public class JavafxPagination extends Application { private Pagination paging; @Override public void start(Stage stage) { // creating pagination with 10 pages and currently selected index as 3 paging = new Pagination(10, 2); // to change the page number paging.setPageFactory(new Callback <Integer, Node>() { @Override public Node call(Integer pageIndex) { return new Label(“Page No.” + (pageIndex + 1)); } }); // creating Vbox that will contain the pagination VBox box = new VBox(); box.getChildren().addAll(paging); box.setAlignment(Pos.CENTER); // creating scene and stage Scene scene = new Scene(box, 400, 300); stage.setScene(scene); stage.setTitle(“Pagination in JavaFX”); stage.show(); } // to launch the application 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 JavafxPagination.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxPagination Output On executing the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – Spinner
JavaFX – Spinner ”; Previous Next A Spinner is a UI control that allows the user to select a value from a predefined range or a ordered sequence. It can be either editable or non-editable. If it is editable, the user can type in a value otherwise not. It also provides up and down arrows so that a user can step through the values of sequence. The figure below illustrates a spinner − Creating a Spinner in JavaFX In JavaFX, the spinner is created by instantiating a class named Spinner. This class belongs to the package javafx.scene.control. Some of the widely used constructors of the Spinner class are listed below − Spinner() − It is used to create an empty spinner. Spinner(double minVal, double maxVal, double initialVal) − It creates a new spinner with the specified minimum, maximum and initial values. Spinner(double minVal, double maxVal, double initialVal, double valToStepBy) − It is used to construct a new spinner with the specified minimum, maximum and initial values along with the increment amount. While creating a spinner in JavaFX, our first step would be instantiating the Spinner class by using any of the above mentioned constructors. The datatype of minimum, maximum and initial values can be either double or integer. Next, define a layout pane, such as Vbox or Hbox by passing the Spinner object to its constructor. Lastly, set the scene and stage to display the spinner on the screen. Example The following JavaFX program demonstrates how to create a spinner in JavaFX application. Save this code in a file with the name JavafxSpinner.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Spinner; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.control.Label; import javafx.geometry.Pos; public class JavafxSpinner extends Application { @Override public void start(Stage stage) { // creating a label Label newlabel = new Label(“Sample Spinner: “); // creating spinner and setting min, max, initial value Spinner newSpinner = new Spinner(0, 100, 25); // vbox to hold spinner VBox vbox = new VBox(newlabel, newSpinner); vbox.setAlignment(Pos.CENTER); // creating stage and scene Scene scene = new Scene(vbox, 400, 300); stage.setScene(scene); stage.setTitle(“Spinner 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 JavafxSpinner.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxSpinner Output When we execute the above code, it will generate the following output. Setting the Size of Spinner To set the size of a spinner, we can use setPrefSize() method. It is a built-in method which accepts heigth and width as a parameter. Example In the following example, we are going to create a Spinner of the specified size in JavaFX application. Save this code in a file with the name DemoSpinner.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Spinner; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; import javafx.stage.Stage; import javafx.scene.control.Label; import javafx.geometry.Pos; public class DemoSpinner extends Application { @Override public void start(Stage stage) { // creating labels for spinner Label newlabel = new Label(“Enter Date of Birth: “); Label setYear = new Label(“Year: “); Label setMonth = new Label(“Month: “); Label setDay = new Label(“Day: “); // creating spinners and setting sizes Spinner year = new Spinner(1998, 2020, 2000); year.setPrefSize(65, 25); Spinner month = new Spinner(1, 12, 1); month.setPrefSize(60, 25); Spinner day = new Spinner(1, 31, 1); day.setPrefSize(60, 25); // HBox to hold labels and spinners HBox box1 = new HBox(); box1.setPadding(new Insets(15, 12, 15, 12)); box1.setSpacing(10); box1.getChildren().addAll(setYear, year, setMonth, month, setDay, day); // VBox to hold HBox and Label VBox box2 = new VBox(); box2.setAlignment(Pos.CENTER); box2.setPadding(new Insets(15, 12, 15, 12)); box2.setSpacing(10); box2.getChildren().addAll(newlabel, box1); // creating scene and stage Scene scene = new Scene(box2, 400, 400); stage.setScene(scene); stage.setTitle(“Spinner in JavaFX”); stage.show(); } public static void main(String[] args) { launch(args); } } Compile and execute the saved Java file from the command prompt by using the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls DemoSpinner.java java –module-path %PATH_TO_FX% –add-modules javafx.controls DemoSpinner Output On executing the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – Creating a Cylinder
JavaFX – Creating a Cylinder ”; Previous Next A cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface. To visualize, you can think of a 3D cylinder as a clutter of 2D circles that are stacked on top of each other to a certain height; hence, making it a three-dimensional shape even though it is described by two parameters. The parameters of a cylinder are – the radius of its circular base and the height of the cylinder as shown in the following diagram − Cylinder in JavaFX In JavaFX, a cylinder is represented by a class named Cylinder. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a cylinder node in JavaFX. This class has 2 properties of the double datatype namely − height − The height of the Cylinder. radius − The radius of the Cylinder. To draw a cylinder, you need to pass values to these properties by passing them to the constructor of this class. This can be done in the same order at the time of instantiation of the Cylinder class; Or, by using their respective setter methods. Steps to Draw 3D Cylinder To Draw a Cylinder (3D) in JavaFX, follow the steps given below. Step 1: Creating a Class Create a Cylinder object in JavaFX by instantiating the class named Cylinder, 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 Cylinder class Cylinder cylinder = new Cylinder(); } } Step 2: Setting Properties to the Cylinder Set the height and radius of the Cylinder using their respective setter as shown below. //Setting the properties of the Cylinder cylinder.setHeight(300.0f); cylinder.setRadius(100.0f); Step 3: Creating a Group Object Now, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Then, pass the Cylinder (node) object created in the previous step as a parameter to the constructor of the Group class. This should be done in order to add it to the group as follows − Group root = new Group(cylinder); 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 Cylinder using JavaFX. Save this code in a file with the name CylinderExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.CullFace; import javafx.scene.shape.Cylinder; import javafx.stage.Stage; public class CylinderExample extends Application { @Override public void start(Stage stage) { //Drawing a Cylinder Cylinder cylinder = new Cylinder(); //Setting the properties of the Cylinder cylinder.setHeight(300.0f); cylinder.setRadius(100.0f); //Creating a Group object Group root = new Group(cylinder); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a cylinder”); //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 CylinderExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CylinderExample Output On executing, the above program generates a JavaFX window displaying a Cylinder as shown below. Example You can also apply transformations on the 3D shape. In this example, we are trying to apply translate transformation on the 3D cylinder and relocate it on the application. Save this code in the file named TranslateCylinderExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.CullFace; import javafx.scene.shape.Cylinder; import javafx.scene.paint.Color; import javafx.scene.transform.Translate; import javafx.stage.Stage; public class TranslateCylinderExample extends Application { @Override public void start(Stage stage) { //Drawing a Cylinder Cylinder cylinder = new Cylinder(); //Setting the properties of the Cylinder cylinder.setHeight(150.0f); cylinder.setRadius(100.0f); Translate translate = new Translate(); translate.setX(200); translate.setY(150); translate.setZ(25); cylinder.getTransforms().addAll(translate); //Creating a Group object Group root = new Group(cylinder); //Creating a scene object Scene scene = new Scene(root, 400, 300); scene.setFill(Color.web(“#81c483”)); //Setting title to the Stage stage.setTitle(“Drawing a cylinder”); //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 TranslateCylinderExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls TranslateCylinderExample Output On executing, the above program generates a JavaFX window displaying a Cylinder as shown below. Print Page Previous Next Advertisements ”;