JavaFX – Drawing a Rectangle ”; Previous Next In general, a rectangle is a four-sided polygon that has two pairs of parallel and concurrent sides with all interior angles as right angles. It is described by two parameters namely − height − The vertical length of the rectangle is known as height. width − The horizontal length of the rectangle is known as width. Rectangle in JavaFX In JavaFX, a Rectangle is represented by a class named Rectangle. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a Rectangle node in JavaFX. This class has 4 properties of the double datatype namely − X − The x coordinate of the start point (upper left) of the rectangle. Y − The y coordinate of the start point (upper left) of the rectangle. Width − The width of the rectangle. height − The height of the rectangle. To draw a rectangle, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation. Steps to Draw a Rectangle You need to follow the steps given below to draw a rectangle in JavaFX. Step 1: Creating a Rectangle To create a rectangle in JavaFX, instantiate the class named Rectangle of the package javafx.scene.shape as shown below − //Creating a rectangle object Rectangle rectangle = new Rectangle(); As the entire code is written within the start() method of Application class, the Rectangle class is also instantiated within it as shown below − public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { // Write code here Rectangle rectangle = new Rectangle(); } } Step 2: Setting Properties to the Rectangle Specify the x, y coordinates of the starting point (upper left), height and the width of the rectangle, that is needed to be drawn. You can do this by setting the properties x, y, height and width, using their respective setter methods. rectangle.setX(150.0f); rectangle.setY(75.0f); rectangle.setWidth(300.0f); rectangle.setHeight(150.0f); Step 3: Adding Rectangle Object to Group In this step, the Group class of package javafx.scene is instantiated by passing the Rectangle object as a parameter value to its constructor as follows − Group root = new Group(rectangle); Step 4: Launching Application Once the 2D object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is the program which generates a rectangle JavaFX. Save this code in a file with the name RectangleExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Rectangle; public class RectangleExample extends Application { @Override public void start(Stage stage) { //Drawing a Rectangle Rectangle rectangle = new Rectangle(); //Setting the properties of the rectangle rectangle.setX(150.0f); rectangle.setY(75.0f); rectangle.setWidth(300.0f); rectangle.setHeight(150.0f); //Creating a Group object Group root = new Group(rectangle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Rectangle”); //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 RectangleExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls RectangleExample Output On executing, the above program generates a JavaFX window displaying a rectangle as shown in the following screenshot. Example – Drawing a House Let us see another example where we try to draw a house using a rectangle. Here, we use two rectangles and two lines to finish a basic version of cartoon house. We will name this file RectangleHouse.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Rectangle; import javafx.scene.shape.Line; import javafx.scene.paint.Color; public class RectangleHouse extends Application { @Override public void start(Stage stage) { //Drawing a Rectangle Rectangle rectangle1 = new Rectangle(); Rectangle rectangle2 = new Rectangle(200.0f, 120.0f, 50.0f, 30.0f); rectangle2.setFill(Color.hsb(50, 1, 1)); //Setting the properties of the rectangle rectangle1.setX(150.0f); rectangle1.setY(75.0f); rectangle1.setWidth(150.0f); rectangle1.setHeight(75.0f); // Setting the properties of Lines // without setter methods Line line1 = new Line(150, 75, 225, 30); Line line2 = new Line(225, 30, 300, 75); //Creating a Group object Group root = new Group(); root.getChildren().addAll(rectangle1, rectangle2, line1, line2); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a House”); //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 RectangleHouse.java java –module-path %PATH_TO_FX% –add-modules javafx.controls RectangleHouse Output On executing, the above program generates a JavaFX window displaying a house as shown in the following screenshot. Print Page Previous Next Advertisements ”;
Category: javafx
JavaFX – Union Operation
JavaFX – Union Operation ”; Previous Next If you look at it mathematically, the Union operation was fundamentally used in the concept of set theory. This operation is defined as the combination of two different sets into one. In here, all the elements of one set and merged within another set, regardless of any duplicities. This concept is then adopted by various techniques in computer programming. For instance, union operation when performed in SQL combines two or more result-sets into one common result set. It is also used in programming languages like C, C++, Java, Python etc. as an operator or a method. Similarly, JavaFX also provides union operation on 2D shapes. Union Operation in JavaFX JavaFX provides union operation which can be performed on 2D shapes. In here, the areas of two or more shapes are combined together to form a bigger and a more complex shape. Thus, the union operation takes two or more shapes as inputs and returns the combined area occupied by them as shown below. You can perform union operation on the shapes using the method called union(). Since this is a static method, you should call it using the class name (Shape or its subclasses) as shown below. Shape shape = Shape.subtract(circle1, circle2); Example Following is an example of the union operation. In here, we are drawing two circles and performing a union operation on them. Save this code in a file with the name unionExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.shape.Shape; public class UnionExample extends Application { @Override public void start(Stage stage) { //Drawing Circle1 Circle circle1 = new Circle(); //Setting the position of the circle circle1.setCenterX(250.0f); circle1.setCenterY(135.0f); //Setting the radius of the circle circle1.setRadius(100.0f); //Setting the color of the circle circle1.setFill(Color.DARKSLATEBLUE); //Drawing Circle2 Circle circle2 = new Circle(); //Setting the position of the circle circle2.setCenterX(350.0f); circle2.setCenterY(135.0f); //Setting the radius of the circle circle2.setRadius(100.0f); //Setting the color of the circle circle2.setFill(Color.BLUE); //Performing union operation on the circle Shape shape = Shape.union(circle1, circle2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Union 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 UnionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls UnionExample Output On executing, the above program generates a JavaFX window displaying the following output − Example Let us try to perform union operation on shapes other than a circle, like an ellipse. Save this file under the name EllipseUnionOperation.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Ellipse; import javafx.scene.shape.Shape; public class EllipseUnionOperation extends Application { @Override public void start(Stage stage) { Ellipse ellipse1 = new Ellipse(); ellipse1.setCenterX(250.0f); ellipse1.setCenterY(100.0f); ellipse1.setRadiusX(150.0f); ellipse1.setRadiusY(75.0f); ellipse1.setFill(Color.BLUE); Ellipse ellipse2 = new Ellipse(); ellipse2.setCenterX(350.0f); ellipse2.setCenterY(100.0f); ellipse2.setRadiusX(150.0f); ellipse2.setRadiusY(75.0f); ellipse2.setFill(Color.RED); Shape shape = Shape.union(ellipse1, ellipse2); //Setting the fill color to the result shape.setFill(Color.DARKSLATEBLUE); //Creating a Group object Group root = new Group(shape); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Union 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 EllipseUnionOperation.java java –module-path %PATH_TO_FX% –add-modules javafx.controls EllipseUnionOperation Output On executing, the above program generates a JavaFX window displaying the following output − Print Page Previous Next Advertisements ”;
JavaFX – Color input Effect
JavaFX – Color Input Effect ”; Previous Next Color Input Effect gives the same output as drawing a rectangle and filling it with color. Unlike other effects, if this effect is applied to any node, it displays only a rectangular box (not the node). This effect is mostly used to pass as an input for other effects. For example, while applying the blend effect, it requires an object of effect type as input. There we can pass this as an input. The class named ColorInput of the package javafx.scene.effect represents the color input effect. This class contains four properties namely − x − This property is of double type; it represents the x coordinate of the position of the color input. y − This property is of double type; it represents the y coordinate of the position of the color input. height − This property is of double type; it represents the height of the region that is to be filled with color. width − This property is of double type; it represents the width of the region that is to be filled with color. paint − This property is of Paint type; it represents the color with which the input region is to be filled. Example Following is an example demonstrating the color input effect. In here, we are creating a color input of the dimensions 50, 400 (height, width) at the position 50, 140, and filling it with the color CHOCOLATE. We are creating rectangle and applying this effect to it. Save this code in a file with the name ColorInputEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.ColorInput; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class ColorInputEffectExample extends Application { @Override public void start(Stage stage) { //creating a rectangle Rectangle rectangle = new Rectangle(); //Instantiating the Colorinput class ColorInput colorInput = new ColorInput(); //Setting the coordinates of the color input colorInput.setX(50); colorInput.setY(140); //Setting the height of the region of the collor input colorInput.setHeight(50); //Setting the width of the region of the color input colorInput.setWidth(400); //Setting the color the color input colorInput.setPaint(Color.CHOCOLATE); //Applying coloradjust effect to the Rectangle rectangle.setEffect(colorInput); //Creating a Group object Group root = new Group(rectangle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Sample Application”); //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 ColorInputEffectExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ColorInputEffectExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Glow Effect
JavaFX – Glow Effect ”; Previous Next Just like the Bloom Effect, the Glow Effect also makes the given input image to glow. This effect makes the pixels of the input much brighter. The class named Glow of the package javafx.scene.effect represents the glow effect. This class contains two properties namely − input − This property is of the type Effect and it represents an input to the glow effect. level − This property is of the type double; it represents intensity of the glow. The range of the level value is 0.0 to 1.0. Example The following program is an example demonstrating the Glow Effect of JavaFX. In here, we are embedding the following image (Tutorialspoint Logo) in JavaFX scene using Image and ImageView classes. This will be done at the position 100, 70 and with fit height and fit width 200 and 400 respectively. To this image, we are applying the Glow Effect with the level value 0.9. Save this code in a file with the name GlowEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.Glow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class GlowEffectExample extends Application { @Override public void start(Stage stage) { //Creating an image Image image = new Image(“http://www.tutorialspoint.com/green/images/logo.png”); //Setting the image view ImageView imageView = new ImageView(image); //setting the fit width of the image view imageView.setFitWidth(200); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //Instantiating the Glow class Glow glow = new Glow(); //setting level of the glow effect glow.setLevel(0.9); //Applying bloom effect to text imageView.setEffect(glow); //Creating a Group object Group root = new Group(imageView); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Sample Application”); //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 GlowEffectExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls GlowEffectExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – LineTo Path Object
JavaFX – LineTo Path Object ”; Previous Next In geometry, a line is one of the most basic figures, which can be combined with other figures in different ways to create more complex structures. For example, a polygon is a closed geomtrical figure that is composed of several lines. In JavaFX, using a primitive 2D shape line to construct such complex figures is quite cumbersome. Thus, we make use of path objects to draw a line from one position to another on a two dimensional plane. Using the Path class, we can draw a 2D shape from one position to another on a plane to create a path object. Previously, we have seen constructing complex figures like Olympics symbols, House etc. by casually using 2D shapes. In this chapter, let us learn how to construct such complex figures using path. JavaFX Path Object LineTo The path element line is used to draw a straight line to a point in the specified coordinates from the current position. It is represented by a class named LineTo. This class belongs to the package javafx.scene.shape. This class has 2 properties of the double datatype namely − X − The x coordinate of the point to which a line is to be drawn from the current position. Y − The y coordinate of the point to which a line is to be drawn from the current position. To draw a line, you need to pass values to these properties. This can be either done by passing them to the constructor of this class, in the same order, at the time of instantiation; Or, by using their respective setter methods. Steps to draw PathElement Line To draw a line to a specified point from the current position in JavaFX, follow the steps given below. Step 1: Creating a Path Class Object Create a Java class and inherit the Application class of the package javafx.application and implement the start() method in this class. Then create a path class object within it as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating a Path object Path path = new Path(); } } Step 2: Setting the Path Create the MoveTo path element and set the XY coordinates to starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below. //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); Step 3: Creating an Object of the Class LineTo Create the path element line by instantiating the class named LineTo which belongs to the package javafx.scene.shape as follows. //Creating an object of the class LineTo LineTo lineTo = new LineTo(); Step 4: Setting Properties to the Line Element Specify the coordinates of the point to which a line is to be drawn from the current position. This can be done by setting the properties x and y using their respective setter methods as shown in the following code block. //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); Step 5: Adding Elements to the Observable List of the Path Class Add the path elements MoveTo and LineTo created in the previous steps to the observable list of the Path class as shown below − //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); Step 6: Launching Application Once the LineTo path object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example 1 The following program shows how to draw a straight line from the current point to a specified position using the class Path of JavaFX. Save this code in a file with the name LineToExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class LineToExample extends Application { @Override public void start(Stage stage) { //Creating a Path object Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); //Instantiating the LineTo class LineTo lineTo = new LineTo(); //Setting the Properties of the line element lineTo.setX(500.0f); lineTo.setY(150.0f); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(lineTo); //Creating a Group object Group root = new Group(path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a Line”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls LineToExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls LineToExample Output On executing, the above program generates a JavaFX window displaying a straight line, which is drawn from the current position to the specified point, as shown below. Example 2 Not just a single line, you can also add multiple lines to the JavaFX application in order to create more complex shapes. In this example, we will try to draw a simple cross figure. Save this code in a file with the name LineToCross.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.LineTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.stage.Stage; public class LineToCross extends Application { @Override public void start(Stage stage) { //Creating a Path object Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); //Instantiating the LineTo class LineTo lineTo = new LineTo(); //Setting
JavaFX – Stroke Type Property ”; Previous Next Two dimensional(2D) shapes, in geometry, are usually referred to as structures that has only two dimensions of measure, commonly length and breadth, and lie on an XY plane. These structures can either be open or closed figures. Open figures include curves like Cubic curve, Quadrilateral curve, etc. whereas closed figures include all types of polygons, circles etc. In JavaFX, these 2D shapes can be drawn on an application by importing the javafx.scene.shape package. However, to improve the quality of a shape, there are various properties and operations that can be performed on it. In this chapter, we will learn about Stroke Type property in detail. Stroke Type Property The Stroke Type property of 2D shapes is used to specify the type of boundary line a 2D shape must have. In JavaFX, this property is set using the StrokeType class. You can set the type of the stroke using the method setStrokeType() as follows − Path.setStrokeType(StrokeType.stroke_type); The stroke_type of a shape can be − Inside − The boundary line will be drawn inside the edge (outline) of the shape (StrokeType.INSIDE). Outside − The boundary line will be drawn outside the edge (outline) of the shape (StrokeType.OUTSIDE). Centered − The boundary line will be drawn in such a way that the edge (outline) of the shape passes exactly thorough the center of the line (StrokeType.CENTERED). By default, the stroke type of a shape is centered. Following is the diagram of a triangle with different Stroke Types − Example Let us see an example demonstrating the usage of StrokeType property on a 2D shape. Save this file with the name StrokeTypeExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Polygon; import javafx.scene.shape.StrokeType; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeTypeExample extends Application { @Override public void start(Stage stage) { //Creating a Triangle Polygon triangle = new Polygon(); //Adding coordinates to the polygon triangle.getPoints().addAll(new Double[]{ 100.0, 50.0, 170.0, 150.0, 100.0, 250.0, }); triangle.setFill(Color.BLUE); triangle.setStroke(Color.BLACK); triangle.setStrokeWidth(7.0); triangle.setStrokeType(StrokeType.CENTERED); //Creating a Group object Group root = new Group(triangle); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Triangle”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeTypeExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeTypeExample Output On executing, the above program generates a JavaFX window displaying a triangle with centered stroke type as shown below. Example Let us see an example demonstrating the usage of INSIDE StrokeType property on a 2D shape. We are using a larger width here in order to properly show the difference between INSIDE and CENTERED stroke types from previous example. Save this file with the name StrokeTypeEllipse.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.shape.Ellipse; import javafx.scene.shape.StrokeType; import javafx.scene.paint.Color; import javafx.stage.Stage; public class StrokeTypeEllipse extends Application { @Override public void start(Stage stage) { //Drawing an ellipse Ellipse ellipse = new Ellipse(); //Setting the properties of the ellipse ellipse.setCenterX(150.0f); ellipse.setCenterY(100.0f); ellipse.setRadiusX(100.0f); ellipse.setRadiusY(50.0f); ellipse.setFill(Color.ORANGE); ellipse.setStroke(Color.BLACK); ellipse.setStrokeWidth(20.0); ellipse.setStrokeType(StrokeType.INSIDE); //Creating a Group object Group root = new Group(ellipse); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a Ellipse”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeTypeEllipse.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StrokeTypeEllipse Output On executing, the above program generates a JavaFX window displaying a triangle with centered stroke type as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Architecture
JavaFX – Architecture ”; Previous Next JavaFX is a software platform that allows developers to build various content-rich client applications, which operate consistently across several platforms. It is a complete API with a rich set of classes and interfaces to build GUI applications with rich graphics. Some of the important packages of this API are − javafx.animation − Contains classes to add transition based animations such as fill, fade, rotate, scale and translation, to the JavaFX nodes. javafx.application − Contains a set of classes responsible for the JavaFX application life cycle. javafx.css − Contains classes to add CSS–like styling to JavaFX GUI applications. javafx.event − Contains classes and interfaces to deliver and handle JavaFX events. javafx.geometry − Contains classes to define 2D objects and perform operations on them. javafx.stage − This package holds the top level container classes for JavaFX application. javafx.scene − This package provides classes and interfaces to support the scene graph. In addition, it also provides sub-packages such as canvas, chart, control, effect, image, input, layout, media, paint, shape, text, transform, web, etc. There are several components that support this rich API of JavaFX. In this chapter, let us learn the architectural design of this JavaFX platform and how its components are interconnected. JavaFX Architecture The following illustration shows the architecture of JavaFX API. Here you can see the components that support JavaFX API. Scene Graph In JavaFX, the GUI Applications were coded using a Scene Graph. A Scene Graph is the starting point of the construction of the GUI Application. It holds the (GUI) application primitives that are termed as nodes. A node is a visual/graphical object and it may include − Geometrical (Graphical) objects − (2D and 3D) such as circle, rectangle, polygon, etc. UI controls − such as Button, Checkbox, Choice box, Text Area, etc. Containers − (layout panes) such as Border Pane, Grid Pane, Flow Pane, etc. Media elements − such as audio, video and image objects. In general, a collection of nodes makes a scene graph. All these nodes are arranged in a hierarchical order as shown below. Each node in the scene graph has a single parent, and the node which does not contain any parents is known as the root node. In the same way, every node has one or more children, and the node without children is termed as leaf node; a node with children is termed as a branch node. A node instance can be added to a scene graph only once. The nodes of a scene graph can have Effects, Opacity, Transforms, Event Handlers, Event Handlers, Application Specific States. Prism Prism is a high performance hardware–accelerated graphical pipeline that is used to render the graphics in JavaFX. It can render both 2-D and 3-D graphics. To render graphics, a Prism uses − DirectX 9 on Windows XP and Vista. DirectX 11 on Windows 7. OpenGL on Mac and Linux, Embedded Systems. In case the hardware support for graphics on the system is not sufficient, then Prism uses the software render path to process the graphics. When used with a supported Graphic Card or GPU, it offers smoother graphics. Just in case the system does not support a graphic card, then Prism defaults to the software rendering stack (either of the above two). GWT (Glass Windowing Toolkit) As the name suggests, GWT provides services to manage Windows, Timers, Surfaces and Event Queues. GWT connects the JavaFX Platform to the Native Operating System. Quantum Toolkit It is an abstraction over the low-level components of Prism, Glass, Media Engine, and Web Engine. It ties Prism and GWT together and makes them available to JavaFX. WebView Using JavaFX, you can also embed HTML content in to a scene graph. WebView is the component of JavaFX which is used to process this content. It uses a technology called Web Kit, which is an internal open-source web browser engine. This component supports different web technologies like HTML5, CSS, JavaScript, DOM and SVG. Using WebView, you can − Render HTML content from local or remote URL. Support history and provide Back and Forward navigation. Reload the content. Apply effects to the web component. Edit the HTML content. Execute JavaScript commands. Handle events. In general, using WebView, you can control web content from Java. Media Engine The JavaFX media engine is based on an open-source engine known as a Streamer. This media engine supports the playback of video and audio content. The JavaFX media engine provides support for audio for the following file formats − Audio MP3 WAV AIFF Video FLV The package javafx.scene.media contains the classes and interfaces to provide media functionality in JavaFX. It is provided in the form of three components, which are − Media Object − This represents a media file Media Player − To play media content. Media View − To display media. Print Page Previous Next Advertisements ”;
JavaFX – Drawing an Arc
JavaFX – Drawing an Arc ”; Previous Next An arc in simple geometry is defined as a portion of a circumference of an ellipse or a circle. Or, simply put, it is a curve that is joins two end points. An arc also encloses an angle less than or equal to 360 degrees at the centre of the circle. It is described by the following properties − length − The distance along the arc. angle − The angle the curve makes at the centre of the circle. radiusX − The width of the full Ellipse of which the current arc is a part of. radiusY − The height of the full Ellipse of which the current arc is a part of. If both radiusX and radiusY are same, then the arc is a part of a circle circumference. Arc in JavaFX In JavaFX, an arc is represented by a class named Arc. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create an arc node in JavaFX. This class has a few properties of the double datatype namely − centerX − The x coordinate of the center of the arc. centerY − The y coordinate of the center of the arc. radiusX − The width of the full ellipse of which the current arc is a part of. radiusY − The height of the full ellipse of which the current arc is a part of. startAngle − The starting angle of the arc in degrees. length − The angular extent of the arc in degrees. To draw an arc, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, or, by using their respective setter methods. Types of Arc In JavaFX, you can draw three kinds of arc’s namely − Open − An arc which is not closed at all is known as an open arc. Chord − A chord is a type of an arc which is closed by straight line. Round − The Round arc is an arc which is closed by joining the starting and ending point to the center of the ellipse. You can set the type of the arc using the method setType() by passing any of the following properties − ArcType.OPEN, ArcType.CHORD, ArcType.Round. Steps to Draw Arc To Draw an arc in JavaFX, follow the steps given below. Step 1: Creating an Arc You can create an arc in JavaFX by instantiating the class named Arc which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method of Application class as shown below. public class ClassName extends Application { public void start(Stage primaryStage) throws Exception { //Creating an object of the class Arc Arc arc = new Arc(); } } Step 2: Setting Properties to the Arc Specify the x, y coordinates of the center of the Ellipse (of which this arc is a part of). These coordinates include – radiusX, radiusY, start angle and length of the arc using their respective setter methods as shown in the following code block. //Setting the properties of the arc arc.setCenterX(300.0f); arc.setCenterY(150.0f); arc.setRadiusX(90.0f); arc.setRadiusY(90.0f); arc.setStartAngle(40.0f); arc.setLength(239.0f); Step 3: Setting the Type of the Arc You can also set the type of the arc (round, chord open) by using the setType() method as shown in the following code block. //Setting the type of the arc arc.setType(ArcType.ROUND); Step 4: Adding Arc Object to Group In the start() method, instantiate a Group class by passing the arc object, which was created in the previous step, as a parameter value to its constructor − Group root = new Group(arc); Step 5: Launching Application Once the 2D object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is a program which generates an arc. Save this code in a file with the name ArcExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; public class ArcExample extends Application { public void start(Stage stage) { //Drawing an arc Arc arc = new Arc(); //Setting the properties of the arc arc.setCenterX(300.0f); arc.setCenterY(150.0f); arc.setRadiusX(90.0f); arc.setRadiusY(90.0f); arc.setStartAngle(40.0f); arc.setLength(239.0f); //Setting the type of the arc arc.setType(ArcType.ROUND); //Creating a Group object Group root = new Group(arc); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing an Arc”); //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 ArcExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ArcExample Output On executing, the above program generates a JavaFX window displaying an arc as shown in the following screenshot. Example Let us try to draw another arc of type “Open” in the following example. Save this code in a file with the name ArcOpen.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.Arc; import javafx.scene.shape.ArcType; public class ArcOpen extends Application { public void start(Stage stage) { //Drawing an arc Arc arc = new Arc(); //Setting the properties of the arc arc.setCenterX(300.0f); arc.setCenterY(150.0f); arc.setRadiusX(90.0f); arc.setRadiusY(90.0f); arc.setStartAngle(40.0f); arc.setLength(239.0f); //Setting the type of the arc arc.setType(ArcType.OPEN); //Creating a Group object Group root = new Group(arc); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing an Open Arc”); //Adding scene to the
JavaFX – Application
JavaFX – Application ”; Previous Next As we have already learned, JavaFX is an open source free software platform, that allows a user to develop client applications that work consistently across various devices. Using JavaFX, one can create Graphical User Interface applications (GUIs), and Internet or Desktop applications as well. All these applications will be developed in Java. In this chapter, we will discuss the structure of a JavaFX application in detail and also learn to create a JavaFX application with an example. JavaFX Application Structure In general, a JavaFX application will have three major components namely Stage, Scene and Nodes as shown in the following diagram. Stage A stage (a window) contains all the objects of a JavaFX application. It is represented by Stage class of the package javafx.stage. The primary stage is created by the platform itself. The created stage object is passed as an argument to the start() method of the Application class (explained in the next section). A stage has two parameters determining its position namely Width and Height. It is divided as Content Area and Decorations (Title Bar and Borders). There are five types of stages available − Decorated Undecorated Transparent Unified Utility You have to call the show() method to display the contents of a stage. Scene A scene represents the physical contents of a JavaFX application. It contains all the contents of a scene graph. The class Scene of the package javafx.scene represents the scene object. At an instance, the scene object is added to only one stage. You can create a scene by instantiating the Scene Class. You can opt for the size of the scene by passing its dimensions (height and width) along with the root node to its constructor. Scene Graph and Nodes A scene graph is a tree-like data structure (hierarchical) representing the contents of a scene. In contrast, a node is a visual/graphical object of a scene graph. A node may include − Geometrical (Graphical) objects (2D and 3D) such as − Circle, Rectangle, Polygon, etc. UI Controls such as − Button, Checkbox, Choice Box, Text Area, etc. Containers (Layout Panes) such as Border Pane, Grid Pane, Flow Pane, etc. Media elements such as Audio, Video and Image Objects. The Node Class of the package javafx.scene represents a node in JavaFX, this class is the super class of all the nodes. A node is of three types − Root Node − The first Scene Graph is known as the Root node. Branch Node/Parent Node − The node with child nodes are known as branch/parent nodes. The abstract class named Parent of the package javafx.scene is the base class of all the parent nodes, and those parent nodes will be of the following types − Group − A group node is a collective node that contains a list of children nodes. Whenever the group node is rendered, all its child nodes are rendered in order. Any transformation, effect state applied on the group will be applied to all the child nodes. Region − It is the base class of all the JavaFX Node based UI Controls, such as Chart, Pane and Control. WebView − This node manages the web engine and displays its contents. Leaf Node − The node without child nodes is known as the leaf node. For example, Rectangle, Ellipse, Box, ImageView, MediaView are examples of leaf nodes. It is mandatory to pass the root node to the scene graph. If the Group is passed as root, all the nodes will be clipped to the scene and any alteration in the size of the scene will not affect the layout of the scene. Creating a JavaFX Application To create a JavaFX application, you need to instantiate the Application class and implement its abstract method start(). In this method, we will write the code for the JavaFX Application. Application Class The Application class of the package javafx.application is the entry point of the application in JavaFX. To create a JavaFX application, you need to inherit this class and implement its abstract method start(). In this method, you need to write the entire code for the JavaFX graphics In the main method, you have to launch the application using the launch() method. This method internally calls the start() method of the Application class as shown in the following program. Example public class JavafxSample extends Application { @Override public void start(Stage primaryStage) throws Exception { /* Code for JavaFX application. (Stage, scene, scene graph) */ } public static void main(String args[]){ launch(args); } } Within the start() method, in order to create a typical JavaFX application, you need to follow the steps given below − Prepare a scene graph with the required nodes. Prepare a Scene with the required dimensions and add the scene graph (root node of the scene graph) to it. Prepare a stage and add the scene to the stage and display the contents of the stage. Preparing the Scene Graph As per your application, you need to prepare a scene graph with required nodes. Since the root node is the first node, you need to create a root node. As a root node, you can choose from the Group, Region or WebView. Group − A Group node is represented by the class named Group which belongs to the package javafx.scene, you can create a Group node by instantiating this class as shown below. Group root = new Group(); The getChildren() method of the Group class gives you an object of the ObservableList class which holds the nodes. We can retrieve this object and add nodes to it as shown below. //Retrieving the observable list object ObservableList list = root.getChildren(); //Setting the text object as a node list.add(NodeObject); We can also add Node objects to the group, just by passing them to the Group class and to its constructor at the time of instantiation, as shown below. Group root = new Group(NodeObject); Region − It is the Base class of all the JavaFX
JavaFX – Drawing a Cubic Curve ”; Previous Next A Cubic Curve is described by a third-degree polynomial function of two variables, and can be written in the following form − These Bezier curves are generally used in computer graphics. They are parametric curves which appear reasonably smooth at all scales. These curves are drawn based on points on the XY plane. A cubic curve is a Bezier parametric curve in the XY plane is a curve of degree 3. It is drawn using four points − Start Point, End Point, Control Point and Control Point2 as shown in the following diagram. Cubic Curve in JavaFX In JavaFX, a Cubic Curve is represented by a class named CubicCurve. This class belongs to the package javafx.scene.shape. By instantiating this class, you can create a CubicCurve node in JavaFX. This class has 8 properties of the double datatype namely − startX − The x coordinate of the starting point of the curve. startY − The y coordinate of the starting point of the curve. controlX1 − The x coordinate of the first control point of the curve. controlY1 − The y coordinate of the first control point of the curve. controlX2 − The x coordinate of the second control point of the curve. controlY2 − The y coordinate of the second control point of the curve. endX − The x coordinate of the end point of the curve. endY − The y coordinate of the end point of the curve. To draw a cubic curve, you need to pass values to these properties, either by passing them to the constructor of this class, in the same order, at the time of instantiation, or by using their respective setter methods. Steps to Draw Cubic Curve To draw a Bezier cubic curve in JavaFX, follow the steps given below. Step 1: Creating a Cubic Curve You can create a Cubic Curve in JavaFX by instantiating the class named CubicCurve which belongs to a package javafx.scene.shape. You can instantiate this class inside the start() method of Application class as follows. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating an object of the class CubicCurve CubicCurve cubiccurve = new CubicCurve(); } } Step 2: Setting Properties to the Cubic Curve Specify the x, y coordinates of the four points: start point, end point, control point1 and control point2 of the required curve, using their respective setter methods as shown in the following code block. //Setting properties to cubic curve cubicCurve.setStartX(100.0f); cubicCurve.setStartY(150.0f); cubicCurve.setControlX1(400.0f); cubicCurve.setControlY1(40.0f); cubicCurve.setControlX2(175.0f); cubicCurve.setControlY2(250.0f); cubicCurve.setEndX(500.0f); cubicCurve.setEndY(150.0f); Step 3: Adding Cubic Curve to Group Instantiate a Group class in the start() method by passing the previously created CubicCurve object as a parameter to its constructor. Group root = new Group(cubiccurve); Step 4: Launching Application Once the 2D object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is a program which generates a Bezier CubicCurve using JavaFX. Save this code in a file with the name CubicCurveExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.CubicCurve; public class CubicCurveExample extends Application { @Override public void start(Stage stage) { //Drawing a cubic curve CubicCurve cubicCurve = new CubicCurve(); //Setting properties to cubic curve cubicCurve.setStartX(100.0f); cubicCurve.setStartY(150.0f); cubicCurve.setControlX1(400.0f); cubicCurve.setControlY1(40.0f); cubicCurve.setControlX2(175.0f); cubicCurve.setControlY2(250.0f); cubicCurve.setEndX(500.0f); cubicCurve.setEndY(150.0f); //Creating a Group object Group root = new Group(cubicCurve); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing a cubic curve”); //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 CubicCurveExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CubicCurveExample Output On executing, the above program generates a JavaFX window displaying a Bezier cubic curve as shown below. Example In the following example, we are trying to apply the DropShadow effect on a Cubic Curve drawn. Save this code in a file with the name CubicCurveEffect.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.DropShadow; import javafx.stage.Stage; import javafx.scene.paint.Color; import javafx.scene.shape.CubicCurve; public class CubicCurveEffect extends Application { @Override public void start(Stage stage) { //Drawing a cubic curve CubicCurve cubicCurve = new CubicCurve(); //Setting properties to cubic curve cubicCurve.setStartX(50.0f); cubicCurve.setStartY(100.0f); cubicCurve.setControlX1(200.0f); cubicCurve.setControlY1(40.0f); cubicCurve.setControlX2(150.0f); cubicCurve.setControlY2(200.0f); cubicCurve.setEndX(200.0f); cubicCurve.setEndY(50.0f); cubicCurve.setFill(Color.RED); //Instantiating the DropShadow class DropShadow ds = new DropShadow(); //Applying DropShadow effect to cubicCurve cubicCurve.setEffect(ds); //Creating a Group object Group root = new Group(cubicCurve); //Creating a scene object Scene scene = new Scene(root, 300, 300); //Setting title to the Stage stage.setTitle(“Drawing a cubic curve”); //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 CubicCurveEffect.java java –module-path %PATH_TO_FX% –add-modules javafx.controls CubicCurveEffect Output On executing, the above program generates a JavaFX window displaying a Bezier cubic curve as shown below. Print Page Previous Next Advertisements ”;