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 ”;
Category: javafx
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 – 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 ”;
JavaFX – Discussion
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 ”;
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 – TextField
JavaFX – TextField ”; Previous Next The text field is a graphical user interface component used to accept user input in the form of text. It is the most easiest way of interaction between system and user. We can find a textfield inside a form or dialog window as shown in the below figure − TextField in JavaFX In JavaFX, the TextField class represents the text field which is a part of the package named javafx.scene.control. Using this we can accept input from the user and read it to our application. This class inherits the TextInputControl which is the base class of all the text controls class. To create a text field, instantiate the TextField class using any of the below constructors − TextField() − This constructor will create an empty textfield. TextField(String str) − It is the parameterized constructor which constructs a textfield with the specified text. Note that in the latest versions of JavaFX, the TextField class accepts only a single line. Example In the following JavaFX program, we will create a hyperlink as a text. Save this code in a file with the name JavafxTextfield.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class JavafxTextfield extends Application { public void start(Stage stage) { //Creating nodes TextField textField1 = new TextField(“Enter your name”); TextField textField2 = new TextField(“Enter your e-mail”); //Creating labels Label label1 = new Label(“Name: “); Label label2 = new Label(“Email: “); //Adding labels for nodes HBox box = new HBox(5); box.setPadding(new Insets(25, 5 , 5, 50)); box.getChildren().addAll(label1, textField1, label2, textField2); //Setting the stage Scene scene = new Scene(box, 595, 150, Color.BEIGE); stage.setTitle(“Text 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 JavafxTextfield.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxTextfield Output When we execute, the above program will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – Fill Transition
JavaFX – Fill Transition ”; Previous Next In the colors section of this tutorial, we have learned that JavaFX nodes can be colored with various colors. However, we had only learned about coloring objects using setFill() method; we can also use animation to change the fill colors of a shape. This type of animation is known as Fill Transition. Fill transition is a type of transition that changes the color of a JavaFX node during a specified period. This transition is commonly used in applications to conduct quizzes: where the option turns “green” if the answer is correct and “red” otherwise. Fill Transition Fill Transition is performed on a JavaFX node using the FillTransition class which belongs to the javafx.animation package. This class contains various properties which can be used to setup the animation on an object. duration − The duration of this FillTransition. shape − The target shape of this FillTransition. fromValue − Specifies the start color value for this FillTransition. toValue − Specifies the stop color value for this FillTransition. Example Following is the program which demonstrates Fill Transition in JavaFX. Save this code in a file with the name FillTransitionExample.java. import javafx.animation.FillTransition; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.util.Duration; public class FillTransitionExample 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(100.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Creating the fill Transition FillTransition fillTransition = new FillTransition(Duration.millis(1000)); //Setting the shape for Transition fillTransition.setShape(circle); //Setting the from value of the transition (color) fillTransition.setFromValue(Color.BLUEVIOLET); //Setting the toValue of the transition (color) fillTransition.setToValue(Color.CORAL); //Setting the cycle count for the transition fillTransition.setCycleCount(50); //Setting auto reverse value to false fillTransition.setAutoReverse(false); //Playing the animation fillTransition.play(); //Creating a Group object Group root = new Group(circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Fill transition example”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls FillTransitionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls FillTransitionExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;