Discuss JavaFX ”; Previous Next JavaFX is a Java library used to build Rich Internet Applications. The applications written using this library can run consistently across multiple platforms. The applications developed using JavaFX can run on various devices such as Desktop Computers, Mobile Phones, TVs, Tablets, etc. To develop GUI Applications using Java programming language, the programmers rely on libraries such as Advanced Windowing Toolkit and Swings. After the advent of JavaFX, these Java programmers can now develop GUI applications effectively with rich content. In this tutorial, we will discuss all the necessary elements of JavaFX that you can use to develop effective Rich Internet Applications. Print Page Previous Next Advertisements ”;
Category: javafx
JavaFX – Useful Resources
JavaFX – Useful Resources ”; Previous Next The following resources contain additional information on JavaFX. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Advanced Java Using Eclipse IDE: Learn JavaFX & Databases Most Popular 34 Lectures 7.5 hours Syed Raza More Detail Complete Oracle JavaFX Bootcamp! Build Real Projects 65 Lectures 12.5 hours Emenwa Global, Ejike IfeanyiChukwu More Detail JavaFX Database Management System! Database Design In JavaFX 20 Lectures 4 hours Emenwa Global, Ejike IfeanyiChukwu More Detail Java GUI 21 Lectures 2.5 hours Marius Claassen More Detail Create A GUI JavaFx Currency Exchange With Clean Java Code 31 Lectures 3.5 hours Gasbaoui Mohammed Al Amine More Detail Print Page Previous Next Advertisements ”;
JavaFX – Stacked Area Chart ”; Previous Next StackedArea Chart is a variation of the Area Chart that displays trends of the contribution of each value (For example – overtime). The areas are stacked so that each series adjoins, but does not overlap the preceding series. This contrasts with the Area chart where each series overlays the preceding series. Following is a Stacked chart depicting population growth. Stacked Area Chart in JavaFX In JavaFX, a Stacked Area chart is represented by a class named StackedAreaChart. This class belongs to the package javafx.scene.chart. By instantiating this class, you can create a StackedAreaChart node in JavaFX. To generate a stacked area chart in JavaFX, follow the steps given below. Step 1: Defining the Axis Define the X and Y axis of the stacked area chart and set labels to them. In our example, X axis represents various years from 1750 to 2050. These have major tick units for every 50 years. While the Y axis represents the population growth in millions. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Defining the X axis CategoryAxis xAxis = new CategoryAxis(); xAxis.setCategories(FXCollections.<String>observableArrayList (Arrays.asList(“1 750”, “1800”, “1850”, “1900”, “1950”, “1999”, “2050” ))); //Defining the Y axis NumberAxis yAxis = new NumberAxis(0, 10000, 2500); yAxis.setLabel(“Population in Billions”); } } Step 2: Creating the Stacked Area Chart Create a line chart by instantiating the class named StackedAreaChart of the package javafx.scene.chart. To the constructor of this class, pass the objects representing the X and Y axis created in the previous step. //Creating the Area chart StackedAreaChart<String, Number> areaChart = new StackedAreaChart(xAxis, yAxis); areaChart.setTitle(“Historic and Estimated Worldwide Population Growth by Region”); Step 3: Preparing the Data Instantiate the XYChart.Series class and add the data (a series of, x and y coordinates) to the Observable list of this class as follows − //Prepare XYChart.Series objects by setting data XYChart.Series series1 = new XYChart.Series(); series1.setName(“Asia”); series1.getData().add(new XYChart.Data(“1750”, 502)); series1.getData().add(new XYChart.Data(“1800”, 635)); series1.getData().add(new XYChart.Data(“1850”, 809)); series1.getData().add(new XYChart.Data(“1900”, 947)); series1.getData().add(new XYChart.Data(“1950”, 1402)); series1.getData().add(new XYChart.Data(“1999”, 3634)); series1.getData().add(new XYChart.Data(“2050”, 5268)); XYChart.Series series2 = new XYChart.Series(); series2.setName(“Africa”); series2.getData().add(new XYChart.Data(“1750”, 106)); series2.getData().add(new XYChart.Data(“1800”, 107)); series2.getData().add(new XYChart.Data(“1850”, 111)); series2.getData().add(new XYChart.Data(“1900”, 133)); series2.getData().add(new XYChart.Data(“1950”, 221)); series2.getData().add(new XYChart.Data(“1999”, 767)); series2.getData().add(new XYChart.Data(“2050”, 1766)); XYChart.Series series3 = new XYChart.Series(); series3.setName(“Europe”); series3.getData().add(new XYChart.Data(“1750”, 163)); series3.getData().add(new XYChart.Data(“1800”, 203)); series3.getData().add(new XYChart.Data(“1850”, 276)); series3.getData().add(new XYChart.Data(“1900”, 408)); series3.getData().add(new XYChart.Data(“1950”, 547)); series3.getData().add(new XYChart.Data(“1999”, 729)); series3.getData().add(new XYChart.Data(“2050”, 628)); XYChart.Series series4 = new XYChart.Series(); series4.setName(“America”); series4.getData().add(new XYChart.Data(“1750”, 18)); series4.getData().add(new XYChart.Data(“1800”, 31)); series4.getData().add(new XYChart.Data(“1850”, 54)); series4.getData().add(new XYChart.Data(“1900”, 156)); series4.getData().add(new XYChart.Data(“1950”, 339)); series4.getData().add(new XYChart.Data(“1999”, 818)); series4.getData().add(new XYChart.Data(“2050”, 1201)); XYChart.Series series5 = new XYChart.Series(); series5.setName(“Oceania”); series5.getData().add(new XYChart.Data(“1750”, 2)); series5.getData().add(new XYChart.Data(“1800”, 2)); series5.getData().add(new XYChart.Data(“1850”, 2)); series5.getData().add(new XYChart.Data(“1900”, 6)); series5.getData().add(new XYChart.Data(“1950”, 13)); series5.getData().add(new XYChart.Data(“1999”, 30)); series5.getData().add(new XYChart.Data(“2050”, 46)); Step 4: Add Data to the Stacked Area Chart Add the data series prepared in the previous step to the stacked area chart as follows − //Setting the data to area chart areaChart.getData().addAll(series1, series2, series3, series4, series5); Step 5: Creating a Group Object In the start() method, create a group object by instantiating the class named Group, which belongs to the package javafx.scene. Pass the StackedAreaChart (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(stackedAreaChart); Step 6: Launching Application Lastly, 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 The following table lists out the population of different continents from year 1750 till year 2050. Asia Africa Europe America Oceania 1750 502 106 163 18 2 1800 635 107 203 31 2 1850 809 111 276 54 2 1900 947 133 408 156 6 1950 1402 221 547 339 13 1999 3634 767 729 818 30 2050 5268 1766 628 1201 46 Following is a Java program which generates a stacked area chart depicting the above data using JavaFX. Save this code in a file with the name StackedAreaChartExample.java. import java.util.Arrays; import javafx.application.Application; import static javafx.application.Application.launch; import javafx.collections.FXCollections; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.chart.CategoryAxis; import javafx.stage.Stage; import javafx.scene.chart.NumberAxis; import javafx.scene.chart.StackedAreaChart; import javafx.scene.chart.XYChart; public class StackedAreaChartExample extends Application { @Override public void start(Stage stage) { //Defining the axes CategoryAxis xAxis = new CategoryAxis(); xAxis.setCategories(FXCollections.<String>observableArrayList( Arrays.asList(“1750”, “1800”, “1850”, “1900”, “1950”, “1999”, “2050” ))); NumberAxis yAxis = new NumberAxis(0, 10000, 2500); yAxis.setLabel(“Population in Millions”); //Creating the Area chart StackedAreaChart<String, Number> areaChart = new StackedAreaChart(xAxis, yAxis); areaChart.setTitle(“Historic and Estimated Worldwide Population Growth by Region”); //Prepare XYChart.Series objects by setting data XYChart.Series series1 = new XYChart.Series(); series1.setName(“Asia”); series1.getData().add(new XYChart.Data(“1750”, 502)); series1.getData().add(new XYChart.Data(“1800”, 635)); series1.getData().add(new XYChart.Data(“1850”, 809)); series1.getData().add(new XYChart.Data(“1900”, 947)); series1.getData().add(new XYChart.Data(“1950”, 1402)); series1.getData().add(new XYChart.Data(“1999”, 3634)); series1.getData().add(new XYChart.Data(“2050”, 5268)); XYChart.Series series2 = new XYChart.Series(); series2.setName(“Africa”); series2.getData().add(new XYChart.Data(“1750”, 106)); series2.getData().add(new XYChart.Data(“1800”, 107)); series2.getData().add(new XYChart.Data(“1850”, 111)); series2.getData().add(new XYChart.Data(“1900”, 133)); series2.getData().add(new XYChart.Data(“1950”, 221)); series2.getData().add(new XYChart.Data(“1999”, 767)); series2.getData().add(new XYChart.Data(“2050”, 1766)); XYChart.Series series3 = new XYChart.Series(); series3.setName(“Europe”); series3.getData().add(new XYChart.Data(“1750”, 163)); series3.getData().add(new XYChart.Data(“1800”, 203)); series3.getData().add(new XYChart.Data(“1850”, 276)); series3.getData().add(new XYChart.Data(“1900”, 408)); series3.getData().add(new XYChart.Data(“1950”, 547)); series3.getData().add(new XYChart.Data(“1999”, 729)); series3.getData().add(new XYChart.Data(“2050”, 628)); XYChart.Series series4 = new XYChart.Series(); series4.setName(“America”); series4.getData().add(new XYChart.Data(“1750”, 18)); series4.getData().add(new XYChart.Data(“1800”, 31)); series4.getData().add(new XYChart.Data(“1850”, 54)); series4.getData().add(new XYChart.Data(“1900”, 156)); series4.getData().add(new XYChart.Data(“1950”, 339)); series4.getData().add(new XYChart.Data(“1999”, 818)); series4.getData().add(new XYChart.Data(“2050”, 1201)); XYChart.Series series5 = new XYChart.Series(); series5.setName(“Oceania”); series5.getData().add(new XYChart.Data(“1750”, 2)); series5.getData().add(new XYChart.Data(“1800”, 2)); series5.getData().add(new XYChart.Data(“1850”, 2)); series5.getData().add(new XYChart.Data(“1900”, 6)); series5.getData().add(new XYChart.Data(“1950”, 13)); series5.getData().add(new XYChart.Data(“1999”, 30)); series5.getData().add(new XYChart.Data(“2050”, 46)); //Setting the data to area chart areaChart.getData().addAll(series1, series2, series3, series4, series5); //Creating a Group object Group root = new Group(areaChart); //Creating a scene object Scene scene
JavaFX – 3D Shapes
JavaFX – 3D Shapes ”; Previous Next In the earlier chapters, we have seen how to draw 2D shapes on an XY plane in a JavaFX application. In addition to these 2D shapes, we can draw several other 3D shapes as well using JavaFX. 3D Shape In general, a 3D shape is a geometrical figure that can be drawn on the XYZ plane. They are defined by two or more dimensions, commonly length, width and depth. 3D shapes supported by JavaFX include a Cylinder, Sphere and a Box. Each of the above mentioned 3D shape is represented by a class and all these classes belong to the package javafx.scene.shape. The class named Shape3D is the base class of all the 3-Dimensional shapes in JavaFX. Creating a 3D Shape To create a 3-Dimensional shape, you need to − Instantiate the respective class of the required 3D shape. Set the properties of the 3D shape. Add the 3D shape object to the group. Instantiating the Respective Class To create a 3-Dimensional shape, first of all you need to instantiate its respective class. For example, if you want to create a 3D box, you need to instantiate the class named Box as follows − Box box = new Box(); Setting the Properties of the Shape After instantiating the class, you need to set the properties for the shape using the setter methods. For example, to draw a 3D box you need to pass its Width, Height, Depth. You can specify these values using their respective setter methods as follows − //Setting the properties of the Box box.setWidth(200.0); box.setHeight(400.0); box.setDepth(200.0); Adding the Shape Object to the Group Finally, you need to add the object of the shape to the group by passing it as a parameter of the constructor as shown below. //Creating a Group object Group root = new Group(box); The following table gives you the list of various 3D shapes provided by JavaFX. S.No Shape & Description 1 Box A cuboid is a three-dimensional shape with a length (depth), width, and a height. In JavaFX a three-dimensional box is represented by a class named Box. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Box node in JavaFX. This class has 3 properties of the double datatype namely − width − The width of the box. height − The height of the box. depth − The depth of the box. 2 Cylinder A cylinder is a closed solid that has two parallel (mostly circular) bases connected by a curved surface. It is described by two parameters, namely, the radius of its circular base and the height of the cylinder. 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. 3 Sphere A sphere is defined as the set of points that are all at the same distance r from a given point in a 3D space. This distance r is the radius of the sphere and the given point is the centre of the sphere. In JavaFX, a sphere is represented by a class named Sphere. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a sphere node in JavaFX. This class has a property named radius of double datatype. It represents the radius of a Sphere. Properties of 3D Objects For all the 3 Dimensional objects, you can set various properties in JavaFX. They are listed below − Cull Face Property Drawing Mode Property Material Property We will discuss the properties of 3D objects in further chapters of this tutorial. Print Page Previous Next Advertisements ”;
JavaFX – Using Convenience Methods ”; Previous Next Event handlers are simply defined as the actions that are to be occurred after an event has taken place. These event handlers can be registered in order to handle more complex events; and you can use convenience methods to register event handlers within your JavaFX application. Event handlers can be created and registered in order to respond to events like mouse events, keyboard events, window events etc. Some JavaFX classes define event handler properties, which provide a way to register event handlers. Setting an event handler property to a user-defined event handler automatically registers the handler to receive the corresponding event type. The setter methods for the event handler properties are convenience methods for registering event handlers. Using Convenience Methods for Event Handling Some of the classes in JavaFX define event handler properties. By setting the values to these properties using their respective setter methods, you can register to an event handler. These methods are known as convenience methods. Most of these methods exist in the classes like Node, Scene, Window, etc., and they are available to all their sub classes. Following table describes various convenience methods that can be used on different events: User Action Event Type EventHandler Properties Pressing, releasing, or typing a key on keyboard. KeyEvent onKeypressed onKeyReleased onKeyTyped Moving, Clicking, or dragging the mouse. MouseEvent onMouseClicked onMouseMoved onMousePressed onMouseReleased onMouseEntered onMouseExited Pressing, Dragging, and Releasing of the mouse button. MouseDragEvent onMouseDragged onMouseDragEntered onMouseDragExited onMouseDragged onMouseDragOver onMouseDragReleased Generating, Changing, Removing or Committing input from an alternate method. InputMethodEvent onInputMethodTextChanged Performing Drag and Drop actions supported by the platform. DragEvent onDragDetected onDragDone onDragDropped onDragEntered onDragExited onDragOver Scrolling an object. ScrollEvent onScroll onScrollStarted onScrollFinished Rotating an object. RotateEvent onRotate onRotationFinished onRotationStarted Swiping an object upwards, downwards, to the right and left. SwipeEvent onSwipeUP onSwipeDown onSwipeLeft onSwipeRight Touching an object. TouchEvent onTouchMoved onTouchReleased onTouchStationary Zooming on an object. ZoomEvent onZoom onZoomStarted onZoomFinished Requesting Context Menu. ContextMenuEvent onContextMenuRequested Pressing a button, showing or hiding a combo box, selecting a menu item. ActionEvent Editing an item in a list. ListView.EditEvent Editing an item in a table. TableColumn.CellEditEvent Editing an item in a tree. TreeView.EditEvent Encountering an error in a media player. MediaErrorEvent Showing or Hiding Menu. Event Hiding a pop-up window. Event Selecting or Closing a Tab. Event Showing, Minimizing, or Closing a Window. WindowEvent Syntax Following is the format of Convenience methods used for registering event handlers: setOnEvent-type(EventHandler<? super event-class> value) For example, to add a mouse event listener to a button, you can use the convenience method setOnMouseClicked() as shown below. playButton.setOnMouseClicked((new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { System.out.println(“Hello World”); pathTransition.play(); } })); Example The following program is an example that demonstrates the event handling in JavaFX using the convenience methods. Save this code in a file with the name ConvenienceMethodsExample.java. import javafx.animation.PathTransition; import javafx.application.Application; import static javafx.application.Application.launch; 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.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; import javafx.util.Duration; public class ConvenienceMethodsExample extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the position of the circle circle.setCenterX(300.0f); circle.setCenterY(135.0f); //Setting the radius of the circle circle.setRadius(25.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Creating a Path Path path = new Path(); //Moving to the staring point MoveTo moveTo = new MoveTo(208, 71); //Creating 1st line LineTo line1 = new LineTo(421, 161); //Creating 2nd line LineTo line2 = new LineTo(226,232); //Creating 3rd line LineTo line3 = new LineTo(332,52); //Creating 4th line LineTo line4 = new LineTo(369, 250); //Creating 5th line LineTo line5 = new LineTo(208, 71); //Adding all the elements to the path path.getElements().add(moveTo); path.getElements().addAll(line1, line2, line3, line4, line5); //Creating the path transition PathTransition pathTransition = new PathTransition(); //Setting the duration of the transition pathTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition pathTransition.setNode(circle); //Setting the path for the transition pathTransition.setPath(path); //Setting the orientation of the path pathTransition.setOrientation( PathTransition.OrientationType.ORTHOGONAL_TO_TAN GENT); //Setting the cycle count for the transition pathTransition.setCycleCount(50); //Setting auto reverse value to true pathTransition.setAutoReverse(false); //Creating play button Button playButton = new Button(“Play”); playButton.setLayoutX(300); playButton.setLayoutY(250); circle.setOnMouseClicked (new EventHandler<javafx.scene.input.MouseEvent>() { @Override public void handle(javafx.scene.input.MouseEvent e) { System.out.println(“Hello World”); circle.setFill(Color.DARKSLATEBLUE); } }); playButton.setOnMouseClicked((new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { System.out.println(“Hello World”); pathTransition.play(); } })); //Creating stop button Button stopButton = new Button(“stop”); stopButton.setLayoutX(250); stopButton.setLayoutY(250); stopButton.setOnMouseClicked((new EventHandler<MouseEvent>() { public void handle(MouseEvent event) { System.out.println(“Hello World”); pathTransition.stop(); } })); //Creating a Group object Group root = new Group(circle, playButton, stopButton); //Creating
JavaFX – UI Controls
JavaFX – UI Controls ”; Previous Next UI Controls are the graphical elements that allow users to interact with an application or a website. They include buttons, menus, sliders, text fields, checkboxes, radio buttons, and more. In this tutorial, we will explore the different types of UI Controls of JavaFX. let”s start the discussion by introducing three main aspects of an user interface − UI elements − These are the core visual elements which the user eventually sees and interacts with. JavaFX provides a huge list of widely used and common elements varying from basic to complex, which we will cover in this tutorial. Layouts − They define how UI elements should be organized on the screen and provide a final look and feel to the GUI (Graphical User Interface). This part will be covered in the Layout chapter. Behavior − These are events which occur when the user interacts with UI elements. This part will be covered in the Event Handling chapter. To create GUI components (controls), JavaFX supports several controls such as date picker, button text field, etc. These controls are represented by different classes of the package javafx.scene.control. We can create a control by instantiating its respective class. Following is the list of common controls used while designing the GUI in JavaFX. S.No Control & Description 1 Label A Label object is a component for placing text. 2 Button This class creates a labeled button. 3 ColorPicker A ColorPicker provides a pane of controls designed to allow a user to manipulate and select a color. 4 CheckBox A CheckBox is a graphical component that can be in either an on(true) or off (false) state. 5 RadioButton The RadioButton class is a graphical component, which can either be in a ON (true) or OFF (false) state in a group. 6 ListView A ListView component presents the user with a scrolling list of text items. 7 TextField A TextField object is a text component that allows for the editing of a single line of text. 8 PasswordField A PasswordField object is a text component specialized for password entry. 9 Scrollbar A Scrollbar control represents a scroll bar component in order to enable user to select from range of values. 10 FileChooser A FileChooser control represents a dialog window from which the user can select a file. 11 ProgressBar As the task progresses towards completion, the progress bar displays the task”s percentage of completion. 12 Slider A Slider lets the user graphically select a value by sliding a knob within a bounded interval. Example The following program is an example which displays a login page in JavaFX. Here, we are using the controls label, text field, password field and button. Save this code in a file with the name LoginPage.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class LoginPage extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text(“Email”); //creating label password Text text2 = new Text(“Password”); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password PasswordField textField2 = new PasswordField(); //Creating Buttons Button button1 = new Button(“Submit”); Button button2 = new Button(“Clear”); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); gridPane.setStyle(“-fx-background-color: BEIGE;”); //Creating a scene object Scene scene = new Scene(gridPane); //Setting title to the Stage stage.setTitle(“CSS 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 LoginPage.java java –module-path %PATH_TO_FX% –add-modules javafx.controls LoginPage Output On executing, the above program generates a JavaFX window as shown below. Example The following program is an example of a registration form, which demonstrates controls in JavaFX such as Date Picker, Radio Button, Toggle Button, Check Box, List View, and Choice List. Save this code in a file with the name Registration.java. import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.CheckBox; import javafx.scene.control.ChoiceBox; import javafx.scene.control.DatePicker; import javafx.scene.control.ListView; import javafx.scene.control.RadioButton; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.control.ToggleButton; import javafx.stage.Stage; public class Registration extends Application { @Override public void start(Stage stage) { //Label for name Text nameLabel = new Text(“Name”); //Text field for name TextField nameText = new TextField(); //Label for date of birth Text dobLabel = new Text(“Date of birth”); //date picker to choose date DatePicker datePicker = new DatePicker(); //Label for gender Text genderLabel = new Text(“gender”); //Toggle group of radio buttons ToggleGroup groupGender = new ToggleGroup(); RadioButton maleRadio = new RadioButton(“male”); maleRadio.setToggleGroup(groupGender); RadioButton femaleRadio = new RadioButton(“female”); femaleRadio.setToggleGroup(groupGender); //Label for reservation Text reservationLabel = new Text(“Reservation”); //Toggle button for reservation ToggleButton Reservation = new ToggleButton(); ToggleButton yes = new ToggleButton(“Yes”); ToggleButton no = new ToggleButton(“No”); ToggleGroup groupReservation = new ToggleGroup(); yes.setToggleGroup(groupReservation); no.setToggleGroup(groupReservation); //Label for technologies known Text technologiesLabel = new Text(“Technologies Known”); //check box for education CheckBox javaCheckBox = new CheckBox(“Java”); javaCheckBox.setIndeterminate(false); //check box for education CheckBox dotnetCheckBox = new CheckBox(“DotNet”); javaCheckBox.setIndeterminate(false); //Label for education Text educationLabel = new Text(“Educational qualification”); //list View for educational qualification ObservableList<String> names = FXCollections.observableArrayList( “Engineering”, “MCA”, “MBA”, “Graduation”, “MTECH”, “Mphil”, “Phd”); ListView<String> educationListView = new ListView<String>(names); //Label for location Text locationLabel = new Text(“location”); //Choice box for location ChoiceBox locationchoiceBox = new ChoiceBox(); locationchoiceBox.getItems().addAll (“Hyderabad”, “Chennai”, “Delhi”, “Mumbai”, “Vishakhapatnam”); //Label for register Button buttonRegister = new Button(“Register”); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(500, 500); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and
JavaFX – CSS
JavaFX – CSS ”; Previous Next CSS, also referred to as Cascading Style Sheet, is a simple design language intended to simplify the process of making web pages presentable and user friendly. It allows us to define the appearance of user interface elements of a web page. Using CSS, we can control the color of the text, style of fonts, spacing between paragraphs, size of columns and layout. Apart from these, we can also control the background images or colors that are used, layout designs, variations in viewport for different devices and screen sizes as well as a variety of other effects. Generally, CSS is widely used in web development, but it can also be applied to JavaFX application. In this tutorial, we are going to learn how to use the CSS in JavaFX application. CSS in JavaFX JavaFX provides us the facility of using CSS to enhance the look and feel of the application. The package javafx.css contains the classes that are used to apply CSS for JavaFX applications. A CSS comprises of style rules that are interpreted by the browser and then applied to the corresponding elements in our document. A style rule is made of three parts, which are as follows − Selector − A selector is an HTML tag at which a style will be applied. This could be any tag like <h1> or <table>, etc. Property − A property is a type of attribute of the HTML tag. In simpler terms, all the HTML attributes are converted into CSS properties. They could be color, border, etc. Value − Values are assigned to properties. For example, a color property can have value either red or #F1F1F1, etc. we can put CSS Style Rule Syntax as follows − selector { property: value } The default style sheet used by JavaFX is modena.css. It is found in the JavaFX runtime jar. Adding Style Sheet in JavaFX we can add our own style sheet to a scene in JavaFX using the getStylesheets() method as shown below − Scene scene = new Scene(new Group(), 500, 400); scene.getStylesheets().add(“path/stylesheet.css”); Adding Inline Style Sheets in JavaFX we can also add in-line styles using the setStyle() method. These styles consist of only key-value pairs and they are applicable to the nodes on which they are set. Following is a sample code of setting an inline style sheet to a button. .button { -fx-background-color: red; -fx-text-fill: white; } Example Assume that we have developed an JavaFX application which displays a form with a Text Field, Password Field, Two Buttons. By default, this form looks as shown in the following screenshot − The following JavaFX code demonstrates how to add styles to the above application using CSS. Save this code in a file with the name CssExample.java. import javafx.application.Application; import static javafx.application.Application.launch; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class CssExample extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text(“Email”); //creating label password Text text2 = new Text(“Password”); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password PasswordField textField2 = new PasswordField(); //Creating Buttons Button button1 = new Button(“Submit”); Button button2 = new Button(“Clear”); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); //Styling nodes button1.setStyle(“-fx-background-color: darkslateblue; -fx-text-fill: white;”); button2.setStyle(“-fx-background-color: darkslateblue; -fx-text-fill: white;”); text1.setStyle(“-fx-font: normal bold 20px ”serif” “); text2.setStyle(“-fx-font: normal bold 20px ”serif” “); gridPane.setStyle(“-fx-background-color: BEIGE;”); // Creating a scene object Scene scene = new Scene(gridPane, 400, 300); // Setting title to the Stage stage.setTitle(“CSS Example in JavaFX”); // 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 CssExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CssExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Images
JavaFX – Images ”; Previous Next Images are one of the most common elements that are used on any application, including JavaFX applications. An image can be in various forms like photographs, graphics or individual video frames etc. There are various digital formats of images which are also supported by JavaFX, they are: BMP GIF JPEG PNG You can load and modify images of all the formats mentioned above using the classes provided by JavaFX in the package javafx.scene.image. This chapter teaches you how to load images in to JavaFX, how to project an image in multiple views and how to alter the pixels of an image. Loading an Image You can load an image in JavaFX by instantiating the class named Image of the package javafx.scene.image. To the constructor of the Image class, you have to pass either of the following as the image source − An InputStream object of the image to be loaded or, A string variable holding the URL for the image. An image can also be resized while they are being loaded, in order to reduce its memory storage amount. This can be done by passing following optional parameters to the constructor of Image class. requestedWidth to set the target width of the displayed image. requestedHeight to set the target height of the displayed image. preserveRatio is a boolean value that specifies whether the aspect ratio of the final image must remain the same as the original image or not. smooth represents the quality of filtering applied on the image. backgroundLoading represents whether the image needs to be loaded in the background or not. Once the image is loaded, you can view it by instantiating the ImageView class. Same image instance can be used by multiple ImageView classes to display it. Syntax Following is the syntax to load and view an Image − //Passing FileInputStream object as a parameter FileInputStream inputstream = new FileInputStream(“C:\images\image.jpg”); Image image = new Image(inputstream); //Loading image from URL //Image image = new Image(new FileInputStream(“url for the image)); After loading the image, you can set the view for the image by instantiating the ImageView class and passing the image to its constructor as follows − ImageView imageView = new ImageView(image); Example Following is an example which demonstrates how to load an image in JavaFX and set the view. Save this code in a file with the name ImageExample.java. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class ImageExample extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating an image Image image = new Image(new FileInputStream(“path of the image”)); //Setting the image view ImageView imageView = new ImageView(image); //Setting the position of the image imageView.setX(50); imageView.setY(25); //setting the fit height and width of the image view imageView.setFitHeight(455); imageView.setFitWidth(500); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 500); //Setting title to the Stage stage.setTitle(“Loading an image”); //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 ImageExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ImageExample Output On executing, the above program generates a JavaFX window as follows − Example In this example, let us try to resize an image (say the previous output image) by passing the final dimensions and the quality of filtering to the constructor of Image class. Save the code in a file named ResizedImageExample.java. import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class ResizedImageExample extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating an image FileInputStream fis = new FileInputStream(“C:/Apache24/htdocs/javafx/images/loading_image.jpg”); Image image = new Image(fis, 250, 300, false, false); //Setting the image view ImageView imageView = new ImageView(image); //Setting the position of the image imageView.setX(50); imageView.setY(25); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 500); //Setting title to the Stage stage.setTitle(“Loading an image”); //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 ResizedImageExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ResizedImageExample Output On executing, the above program generates a JavaFX window as follows − Multiple Views of an Image In some cases, an application requires an image to be displayed in different ways: with different dimensions, with better quality, after scaling, etc. Instead of creating a new application every time a different view of Image is needed, JavaFX allows you to set multiple views for an image in the same scene. Once an image is loaded using the Image class, multiple ImageView objects can be created by instantiating the ImageView class multiple times. The ImageView class is a JavaFX Node that paints images that are loaded using the Image class. This class can be instantiated multiple times in a the start() method of Application class in order to display multiple views of an image. These multiple views can vary in their sizes, quality or be the exact copy of the original. However, to do so, you need to pass an Image object or a URL string of the source image. The syntax to create an ImageView object is as follows − Syntax // A new ImageView object is allocated ImageView = new ImageView() // ImageView object is allocated using // the given Image object ImageView imageview = new ImageView(Image image) // ImageView object is allocated using // the image loaded from a URL ImageView imageview = new ImageView(String URL) Example The following program is an example that demonstrates how to set various views for an image in
JavaFX – Layout Panes
JavaFX – Layout Panes(Containers) ”; Previous Next After constructing all the required nodes in a scene, we generally arrange them in the desired order. The container in which we arrange the components is called the Layout of the container. We can also say that we followed a layout as it helps in placing all the components at a particular position within the container. Below is a diagram illustrating the positioning of JavaFX nodes in vertical and horizontal layout. In this tutorial, we are going to discuss various predefined layouts provided by JavaFX including HBox, VBox, Border Pane, Stack Pane, Text Flow, Anchor Pane, Title Pane, Grid Pane, Flow Panel, and so on. Each of the above mentioned layout is represented by a class and all these classes belongs to the package named javafx.layout. The class named Pane is the base class of all the layouts in JavaFX. Creating a Layout To create a layout, we need to follow the given steps − Create node. Instantiate the respective class of the required layout. Set the properties of the layout. Add all the created nodes to the layout. Creating Nodes First of all, create the required nodes of the JavaFX application by instantiating their respective classes. For example, if we want to have a text field and two buttons namely, play and stop in a HBox layout, we will have to initially create those nodes as shown in the following code block − //Creating a text field TextField textField = new TextField(); //Creating the play button Button playButton = new Button(“Play”); //Creating the stop button Button stopButton = new Button(“stop”); Instantiating the Respective Class After creating the nodes (and completing all the operations on them), instantiate the class of the required layout. For example, if we want to create a Hbox layout, we need to instantiate this class as follows − HBox hbox = new HBox(); Setting the Properties of the Layout After instantiating the class, we need to set the properties of the layout using their respective setter methods. For instance − If we want to set space between the created nodes in the HBox layout, then we need to set value to the property named spacing. This can be done by using the setter method setSpacing() as shown below − hbox.setSpacing(10); Adding the node Objects to the Layout Pane Finally, we need to add the objects of the created nodes to the layout pane by passing them as a parameter value as shown below − //Creating a Group object hbox.getChildren().addAll(textField, playButton, stopButton); Layout Panes in JavaFX Following are the various Layout panes (classes) provided by JavaFX. These classes exist in the package javafx.scene.layout. S.No Layouts & Description 1 HBox The HBox layout arranges all the nodes in our application in a single horizontal row. The class named HBox of the package javafx.scene.layout represents the text horizontal box layout. 2 VBox The VBox layout arranges all the nodes in our application in a single vertical column. The class named VBox of the package javafx.scene.layout represents the text Vertical box layout. 3 BorderPane The Border Pane layout arranges the nodes in our application in top, left, right, bottom and center positions. The class named BorderPane of the package javafx.scene.layout represents the border pane layout. 4 StackPane The stack pane layout arranges the nodes in our application on top of another just like in a stack. The node added first is placed at the bottom of the stack and the next node is placed on top of it. The class named StackPane of the package javafx.scene.layout represents the stack pane layout. 5 TextFlow The Text Flow layout arranges multiple text nodes in a single flow. The class named TextFlow of the package javafx.scene.layout represents the text flow layout. 6 AnchorPane The Anchor pane layout anchors the nodes in our application at a particular distance from the pane. The class named AnchorPane of the package javafx.scene.layout represents the Anchor Pane layout. 7 TilePane The Tile Pane layout adds all the nodes of our application in the form of uniformly sized tiles. The class named TilePane of the package javafx.scene.layout represents the TilePane layout. 8 GridPane The Grid Pane layout arranges the nodes in our application as a grid of rows and columns. This layout comes handy while creating forms using JavaFX. The class named GridPane of the package javafx.scene.layout represents the GridPane layout. 9 FlowPane The flow pane layout wraps all the nodes in a flow. A horizontal flow pane wraps the elements of the pane at its height, while a vertical flow pane wraps the elements at its width. The class named FlowPane of the package javafx.scene.layout represents the Flow Pane layout. Print Page Previous Next Advertisements ”;
JavaFX – GridPane Layout
JavaFX – GridPane Layout ”; Previous Next GridPane Layout in JavaFX The GridPane is a type of layout container in which all the nodes are arranged in such a way that they form a grid of rows and columns. This layout comes handy while creating forms, charts, media galleries and so on. In JavaFX, the class named GridPane of the package javafx.scene.layout represents the GridPane layout. Instantiating this class using its default constructor will create a grid pane layout in our JavaFX application. This class provides the following properties − alignment − This property represents the alignment of the pane and you can set value of this property using the setAlignment() method. hgap − This property is of the type double and it represents the horizontal gap between columns. vgap − This property is of the type double and it represents the vertical gap between rows. gridLinesVisible − This property is of Boolean type. On true, the lines of the pane are set to be visible. Following table illustrates the cell positions in the grid pane of JavaFX. The first value of each cell represents row and second one column. (0, 0) (1, 0) (2, 0) (0, 1) (1, 1) (2, 1) (0, 2) (1, 2) (2, 2) Example The following program is an example of the grid pane layout. In this, we are creating a form using a Grid Pane. Save this code in a file with the name GridPaneExample.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.GridPane; import javafx.scene.text.Text; import javafx.scene.control.TextField; import javafx.stage.Stage; public class GridPaneExample extends Application { @Override public void start(Stage stage) { //creating label email Text text1 = new Text(“Email”); //creating label password Text text2 = new Text(“Password”); //Creating Text Filed for email TextField textField1 = new TextField(); //Creating Text Filed for password TextField textField2 = new TextField(); //Creating Buttons Button button1 = new Button(“Submit”); Button button2 = new Button(“Clear”); //Creating a Grid Pane GridPane gridPane = new GridPane(); //Setting size for the pane gridPane.setMinSize(400, 200); //Setting the padding gridPane.setPadding(new Insets(10, 10, 10, 10)); //Setting the vertical and horizontal gaps between the columns gridPane.setVgap(5); gridPane.setHgap(5); //Setting the Grid alignment gridPane.setAlignment(Pos.CENTER); //Arranging all the nodes in the grid gridPane.add(text1, 0, 0); gridPane.add(textField1, 1, 0); gridPane.add(text2, 0, 1); gridPane.add(textField2, 1, 1); gridPane.add(button1, 0, 2); gridPane.add(button2, 1, 2); //Creating a scene object Scene scene = new Scene(gridPane, 400, 300); //Setting title to the Stage stage.setTitle(“Grid Pane Example in JavaFX”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage 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 GridPaneExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls GridPaneExample Output On executing, the above program will generate a JavaFX window displaying a form built using GridPane layout. Print Page Previous Next Advertisements ”;