JavaFX – Tooltip ”; Previous Next The tooltip is a small pop-up window that displays some additional information when the user hovers over a node or a control. It is mainly used for explaining the functionality of a button, menu, or image or to provide some hints for a text field. In the below figure, we can see the tooltip explaining the menu”s functionality − Tooltip in JavaFX In JavaFX, the tooltip is represented by a class named Tooltip which is a part of javafx.scene.control package. Each UI component of this package comes with a built-in method named setTooltip() which is used for associating a tooltip. We can specify the tooltip text either by passing it to the setText() method or by using the constructor listed below − Tooltip() − It is the default constructor that constructs a tooltip without any texts. Tooltip(String str) − It constructs a new tooltip with the predefined text. Steps to create a tooltip in JavaFX To create a Tooltip in JavaFX, follow the steps given below. Step 1: Create a node to associate with Tooltip We know that a tooltip explains the features of specified node. This node can be any JavaFX component such as menu, image and text fields. Here, we are going to use an image as a node. To create an image in JavaFX, instantiate the ImageView class and pass the path of image as a parameter value to its constructor. //Passing path of an image Image image = new Image(new FileInputStream(“tutorials_point.jpg”)); //Setting the image view ImageView imageView = new ImageView(image); Step 2: Instantiate the Tooltip class To create a tooltip in JavaFX, instantiate the Tooltip class and pass the tooltip text as a parameter value to its constructor using the below code − //Creating tool tip for the given image Tooltip toolTipTxt = new Tooltip(“This is the new logo of Tutorialspoint”); Step 3: Associate the tooltip to the node To associate the Tooltip to the specified node, we use the install() mehtod which accepts Tooltip and ImageView objects as arguments. //Setting the tool tip to the image Tooltip.install(imageView, toolTipTxt); Step 4: Launching Application After creating the Tooltip, follow the given steps below to launch the application properly − Firstly, create a VBox that holds the nodes vertically. Next, instantiate the class named Scene by passing the VBox object as a parameter value to its constructor along with the dimensions of the application screen. Then, set the title of the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example In the following example, we are going to create a tooltip in JavaFX application. Save this code in a file with the name JavafxTooltip.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.control.Tooltip; import javafx.scene.layout.VBox; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.stage.Stage; public class JavafxTooltip extends Application { @Override public void start(Stage stage) throws FileNotFoundException { //Creating a label Label labeltext = new Label(“Hover over Image to see the details….”); //Passing path of an image Image image = new Image(new FileInputStream(“tutorials_point.jpg”)); //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(350); imageView.setFitWidth(350); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //Creating tool tip for the given image Tooltip toolTipTxt = new Tooltip(“This is the new logo of Tutorialspoint”); //Setting the tool tip to the image Tooltip.install(imageView, toolTipTxt); // to display the content vertically VBox box = new VBox(5); box.setPadding(new Insets(25, 5 , 5, 50)); box.getChildren().addAll(labeltext, imageView); //Setting the stage Scene scene = new Scene(box, 400, 350); stage.setTitle(“Example of Tooltip in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } To compile and execute the saved Java file from the command prompt, use the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxTooltip.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxTooltip Output When we execute the above code, it will generate a Tooltip for an image as shown in the following output. Adding icons to the Tooltip Icons are small images that graphically illustrate a command or function of an application. To add icons to the JavaFX tooltip, we use the setGraphic() method which accepts the ImageView object and displays the icon on the left of tooltip text. Example Following is the JavaFX program that will create a Tooltip with icon. Save this code in a file with the name JavafxTooltip.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.control.Tooltip; import javafx.scene.layout.VBox; import java.io.FileInputStream; import java.io.FileNotFoundException; import javafx.stage.Stage; public class JavafxTooltip extends Application { public void start(Stage stage) throws FileNotFoundException { // Creating a label Label labeltext = new Label(“Hover over this text to see the tooltip….”); // Instantiating Tooltip class Tooltip toolT = new Tooltip(); // Passing path of an image Image icon = new Image(new FileInputStream(“faviconTP.png”)); // adding the icon for tooltip toolT.setGraphic(new ImageView(icon)); // adding the text toolT.setText(“This is the new logo of Tutorialspoint”); // setting the tooltip to the label labeltext.setTooltip(toolT); //Setting the stage Scene scene = new Scene(labeltext, 400, 300); stage.setTitle(“Example of Tooltip in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands − javac –module-path %PATH_TO_FX% –add-modules
Category: javafx
JavaFX – Accordion
JavaFX – Accordion ”; Previous Next An accordion serves as a container for one or more title panels. These title panels are a panel with titles and they can be expanded or collapsed by clicking on their headers. However, only one title pane is allowed to open at a time. An accordion is useful for organizing the UI into sections that can be hidden or shown as needed. The below figure depicts an Accordion − Accordion in JavaFX In JavaFX, an accordion is represented by a class named Accordion. This class belongs to the package javafx.scene.control. By instantiating this class, we can create an Accordion node in JavaFX. Two constructors are available for this class, and they are as follows − Accordion() − It is used for creating an accordion without TitledPane. Accordion(…TitledPanes) − It will create an accordion with the specified TitledPane. Steps to create an Accordion in JavaFX Follow the steps given below to create an accordion in JavaFX. Step 1: Create two or more TitledPane We can create title panes in JavaFX by instantiating the class named TitledPane which belongs to a package javafx.scene.control. Instantiate this class as shown below − //Creating a TitledPane object TitledPane paneOne = new TitledPane(); Similarly, create the required number of title panes. Step 2: Set title and contents to the TitledPane Specify the title and content of the title pane using the setText() and setContent() methods respectively as shown in the following code block. paneOne.setText(“Your Name”); paneOne.setContent(new Label(“My name is: n Ansh”)); Remember, we can customize the content of the TitledPane as per our requirements with different UI nodes of JavaFX. Step 3: Instantiate Accordion class Instantiate the Accordion class of package javafx.scene.control without passing any parameter value to its constructor and add all the TitledPane using the following code blocks − Accordion accordionNew = new Accordion(); accordionNew.getPanes().addAll(paneOne, paneTwo, paneThree); Step 4: Launching Application Once the accordion is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named VBox by passing the Accordion object as a parameter value to its constructor. Then, instantiate the class named Scene by passing the VBox object as a parameter value to its constructor. We can also pass dimensions of the application screen as optional parameters to this constructor. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is the program which will create an accordion using JavaFX. Save this code in a file with the name JavafxAccordion.java. import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Accordion; import javafx.scene.control.TitledPane; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class JavafxAccordion extends Application { @Override public void start(Stage stage) { //Creating the first TitledPane TitledPane paneOne = new TitledPane(); paneOne.setText(“Your Name”); paneOne.setContent(new Label(“My name is: n Ansh”)); //Creating the second TitledPane TitledPane paneTwo = new TitledPane(); paneTwo.setText(“Your Address”); paneTwo.setContent(new Label(“My address is: n Hyderabad n Telangana”)); //Creating the third TitledPane TitledPane paneThree = new TitledPane(); paneThree.setText(“Your Job”); paneThree.setContent(new Label(“My job role is: n Content Engineer”)); //Creating an Accordion for all TitledPane Accordion accordionNew = new Accordion(); accordionNew.getPanes().addAll(paneOne, paneTwo, paneThree); accordionNew.setExpandedPane(paneOne); VBox root = new VBox(accordionNew); //Setting the stage Scene scene = new Scene(root, 500, 500, Color.BEIGE); stage.setTitle(“Accordion in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxAccordion.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxAccordion Output On executing, the above program generates a JavaFX window displaying an accordion as shown below. Creating an Accordion in JavaFX using its parameterized constructor As previously discussed, there are two ways to create an Accordion in JavaFX: one utilizes the default constructor of Accordion class, while the other uses its parameterized constructor. In the next example, we are going to use the parameterized constructor of the Accordion class to create an accordion in JavaFX. Save this Java code in a file with the name JavafxAccordion.java. Example import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.Accordion; import javafx.scene.control.TitledPane; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class JavafxAccordion extends Application { @Override public void start(Stage stage) { //Creating the first TitledPane TitledPane paneOne = new TitledPane(); paneOne.setText(“Your Name”); paneOne.setContent(new Label(“My name is: n Ansh”)); //Creating the second TitledPane TitledPane paneTwo = new TitledPane(); paneTwo.setText(“Your Address”); paneTwo.setContent(new Label(“My address is: n Hyderabad n Telangana”)); //Creating the third TitledPane TitledPane paneThree = new TitledPane(); paneThree.setText(“Your Job”); paneThree.setContent(new Label(“My job role is: n Content Engineer”)); //Creating an Accordion for all TitledPane Accordion accordionNew = new Accordion(paneOne, paneTwo, paneThree); accordionNew.setExpandedPane(paneThree); VBox root = new VBox(accordionNew); //Setting the stage Scene scene = new Scene(root, 500, 500, Color.BEIGE); stage.setTitle(“Accordion in JavaFX”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxAccordion.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxAccordion Output When we execute the above code, it will generate the following output. Print Page Previous Next Advertisements ”;
JavaFX – Scale Transition
JavaFX – Scale Transition ”; Previous Next As its name suggests, scaling refers to increasing or decreasing the size of an object. In computer graphics, by applying the scale transition on an object (or image), you can either increase or decrease its size, for a specified duration. This transition can also be applied on various JavaFX nodes, on 2D shapes, 3D shapes, text, and any other element on an application. Scale Transition in JavaFX The Scale transition is performed in JavaFX using the ScaleTransition class which belongs to the javafx.animation package. This class contains various properties that assist in playing this animation on a JavaFX application − byX − Specifies the incremented stop X scale value, from the start, of this ScaleTransition. byY − Specifies the incremented stop Y scale value, from the start, of this ScaleTransition. byZ − Specifies the incremented stop Z scale value, from the start, of this ScaleTransition. duration − The duration of this ScaleTransition fromX − Specifies the start X scale value of this ScaleTransition. fromY − Specifies the start Y scale value of this ScaleTransition. fromZ − Specifies the start Z scale value of this ScaleTransition. node − The target node of this ScaleTransition. toX − Specifies the stop X scale value of this ScaleTransition. toY − The stop Y scale value of this ScaleTransition. toZ − The stop Z scale value of this ScaleTransition. Example Following is the program which demonstrates Scale Transition in JavaFX. Save this code in a file with the name ScaleTransitionExample.java. import javafx.animation.ScaleTransition; import javafx.application.Application; import static javafx.application.Application.launch; 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 ScaleTransitionExample 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(50.0f); //Setting the color of the circle circle.setFill(Color.BROWN); //Setting the stroke width of the circle circle.setStrokeWidth(20); //Creating scale Transition ScaleTransition scaleTransition = new ScaleTransition(); //Setting the duration for the transition scaleTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition scaleTransition.setNode(circle); //Setting the dimensions for scaling scaleTransition.setByY(1.5); scaleTransition.setByX(1.5); //Setting the cycle count for the translation scaleTransition.setCycleCount(50); //Setting auto reverse value to true scaleTransition.setAutoReverse(false); //Playing the animation scaleTransition.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(“Scale 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 ScaleTransitionExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ScaleTransitionExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – ListView
JavaFX – ListView ”; Previous Next The ListView is a graphical user interface component used for displaying a list of items from which a user can select desired items. Generally, a list refers to a group or collection of items. It helps in organizing, structuring and presenting information in more user-friendly and readable way. The figure below illustrates a list view of cities from which a user can choose one option − ListView in JavaFX In JavaFX, the list view is represented by a class named ListView which is a part of javafx.scene.control package. We can create a list view component by instantiating this class. Additionally, we have the option to select its orientation, allowing it to be displayed either vertically or horizontally. List of constructors of the ListView class is as follows − ListView() − It is the default constructor that constructs a vertical list view. ListView(ObservableList<type> listItems) − It constructs a new vertical list view with the specified list items. Creating ListView in JavaFX To create a ListView in any JavaFX application, we can use either the default contructor or the parameterized constructor of the ListView class. If the default constructor is used, we should pass the list items explicitly. The parameterized constructor accepts an ArrayList object as a parameter value as shown in the below code block − //list View for educational qualification ObservableList<String> names = FXCollections.observableArrayList(“Engineering”, “MCA”, “MBA”, “Graduation”, “MTECH”, “Mphil”, “Phd”); ListView<String> listView = new ListView<String>(names); Once the ListView class is instantiated and its items are added, define any layout pane such VBox or HBox to hold the list view. Next, create a Scene object by passing the layout pane obejct and the dimensions of the Scene to its constructor. Then, set the stage and launch the application to display the result. Example In the following example, we are going to demonstrates how to create ListView in JavaFX. Save this code in a file with the name JavafxListview.java. import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ListView; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class JavafxListview extends Application { public void start(Stage stage) { //Label for education Label label = new Label(“Educational qualification:”); Font font = Font.font(“verdana”, FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //list View for educational qualification ObservableList<String> names = FXCollections.observableArrayList(“Engineering”, “MCA”, “MBA”, “Graduation”, “MTECH”, “Mphil”, “Phd”); ListView<String> listView = new ListView<String>(names); listView.setMaxSize(200, 160); //Creating the layout VBox layout = new VBox(10); layout.setPadding(new Insets(5, 5, 5, 50)); layout.getChildren().addAll(label, listView); layout.setStyle(“-fx-background-color: BEIGE”); //Setting the stage Scene scene = new Scene(layout, 400, 300); stage.setTitle(“List View Example”); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved Java file from the command prompt using the following commands − javac –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxListview.java java –module-path %PATH_TO_FX% –add-modules javafx.controls JavafxListview Output On executing the above code, it will generate a window displaying a ListView as shown in the below output − Print Page Previous Next Advertisements ”;
JavaFX – Color Adjust Effect
JavaFX – Color Adjust Effect ”; Previous Next The most basic effect that can be performed on any image is adjusting its color. Various image processing applications allow you to do it. Similarly, JavaFX also allows you to adjust a color of an image in an application. You can adjust the color of an image by applying the color adjust effect to it. This includes the adjustment of the Hue, Saturation, Brightness and Contrast on each pixel. The class named ColorAdjust of the package javafx.scene.effect represents the color adjust effect, this class contains five properties namely − input − This property is of the Effect type and it represents an input to the color adjust effect. brightness − This property is of Double type and it represents the brightness adjustment value for this effect. contrast − This property is of Double type and it represents the contrast adjustment value for this effect. hue − This property is of Double type and it represents the hue adjustment value for this effect. saturation − This property is of Double type and it represents the saturation adjustment value for this effect. Example The following program is an example of demonstrating the color adjust effect. In here, we are embedding an image (Tutorialspoint Logo) in JavaFX scene using Image and ImageView classes. This is being done at the position 100, 70 and with a fit height and fit width of 200 and 400 respectively. We are adjusting the color of this image using the color adjust effect. With contrast, hue, brightness and saturation values as 0.4. -0.05, 0.9, 0.8. Save this code in a file with the name ColorAdjustEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.ColorAdjust; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.stage.Stage; public class ColorAdjustEffectExample 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 position of the image imageView.setX(100); imageView.setY(70); //setting the fit height and width of the image view imageView.setFitHeight(200); imageView.setFitWidth(400); //Setting the preserve ratio of the image view imageView.setPreserveRatio(true); //Instantiating the ColorAdjust class ColorAdjust colorAdjust = new ColorAdjust(); //Setting the contrast value colorAdjust.setContrast(0.4); //Setting the hue value colorAdjust.setHue(-0.05); //Setting the brightness value colorAdjust.setBrightness(0.9); //Setting the saturation value colorAdjust.setSaturation(0.8); //Applying coloradjust effect to the ImageView node imageView.setEffect(colorAdjust); //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(“Coloradjust effect 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 ColorAdjustEffectExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls ColorAdjustEffectExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – Radial Gradient Pattern ”; Previous Next Like Linear Gradient Pattern, there are various types of gradient patterns that depict the way they”re flowed. The other types are Radial, Angular, Reflected, Diamond gradient patterns. In this chapter, we will learn about the Radial Gradient Pattern. The Radial Gradient Pattern is another type of gradient pattern that starts from a center point and flows in a circular manner up to a radius. Simply put, the radial gradient contains two or more color stops in the form of concentric circles. JavaFX also provides this type of color pattern to fill circular type of 2D shapes, like a regular circle or an ellipse etc. Applying Radial Gradient Pattern To apply a Radial Gradient Pattern to the nodes, instantiate the GradientPattern class and pass its object to the setFill(), setStroke() methods. The constructor of this class accepts a few parameters, some of which are − startX, startY − These double properties represent the x and y coordinates of the starting point of the gradient. endX, endY − These double properties represent the x and y coordinates of the ending point of the gradient. cycleMethod − This argument defines how the regions outside the color gradient bounds are defined by the starting and ending points and how they should be filled. proportional − This is a Boolean Variable; on setting this property to true the start and end locations are set to a proportion. Stops − This argument defines the color-stop points along the gradient line. //Setting the radial gradient Stop[] stops = new Stop[] { new Stop(0.0, Color.WHITE), new Stop(0.3, Color.RED), new Stop(1.0, Color.DARKRED) }; RadialGradient radialGradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops); Example Following is an example which demonstrates how to apply a radial gradient pattern to the nodes in JavaFX. Here, we are creating a circle and a text nodes and applying gradient pattern to them. Save this code in a file with the name RadialGradientExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; import javafx.stage.Stage; import javafx.scene.shape.Circle; import javafx.scene.text.Font; import javafx.scene.text.Text; public class RadialGradientExample extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(); //Setting the properties of the circle circle.setCenterX(300.0f); circle.setCenterY(180.0f); circle.setRadius(90.0f); //Drawing a text Text text = new Text(“This is a colored circle”); //Setting the font of the text text.setFont(Font.font(“Edwardian Script ITC”, 50)); //Setting the position of the text text.setX(155); text.setY(50); //Setting the radial gradient Stop[] stops = new Stop[] { new Stop(0.0, Color.WHITE), new Stop(0.3, Color.RED), new Stop(1.0, Color.DARKRED) }; RadialGradient radialGradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops); //Setting the radial gradient to the circle and text circle.setFill(radialGradient); text.setFill(radialGradient); //Creating a Group object Group root = new Group(circle, text); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Radial Gradient 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 RadialGradientExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls RadialGradientExample Output On executing, the above program generates a JavaFX window as follows − Example Radial Gradient Pattern does not work with shapes that are non-circular; i.e., you can only apply radial gradient on circular and elliptical shapes. In the following example, let us try to apply the radial gradient pattern on a Rectangular shape. Save this code in a file with the name RectangleRadialGradient.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.scene.paint.CycleMethod; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; import javafx.stage.Stage; import javafx.scene.shape.Rectangle; public class RectangleRadialGradient extends Application { @Override public void start(Stage stage) { Rectangle rct = new Rectangle(50.0f, 50.0f, 200.0f, 100.0f); Stop[] stops = new Stop[] { new Stop(0.0, Color.WHITE), new Stop(0.3, Color.RED), new Stop(1.0, Color.DARKRED) }; RadialGradient radialGradient = new RadialGradient(0, 0, 300, 178, 60, false, CycleMethod.NO_CYCLE, stops); rct.setFill(radialGradient); Group root = new Group(rct); Scene scene = new Scene(root, 300, 300); stage.setTitle(“Radial Gradient Example”); stage.setScene(scene); stage.show(); } public static void main(String args[]) { launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls RectangleRadialGradient.java java –module-path %PATH_TO_FX% –add-modules javafx.controls RectangleRadialGradient Output On executing, you will only see the outermost color of the gradient in the shape as follows − Print Page Previous Next Advertisements ”;
JavaFX – Lighting Effect
JavaFX – Lighting Effect ”; Previous Next The lighting effect is used to simulate a light from a light source. There are different kinds of light sources which include − Point, Distant and Spot. If we do not mention any source for lighting, it uses the default source of JavaFX. The class named Lighting of the package javafx.scene.effect represents the lighting effect, this class contains ten properties, which are − bumpInput − This property is of the type Effect and it represents an optional bump map input to the lighting effect. contentInput − This property is of the type Effect and it represents a content input to the lighting effect. diffuseConstant − This property is of the type double and it represents the diffuse constant of the light. SpecularConstant − This property is of the type double and it represents the specular constant of the light. SpecularExponent − This property is of the type double and it represents the specular exponent of the light. SurfaceScale − This property is of the type double and it represents the surface scale factor of the light. Example The following program is an example demonstrating the lighting effect of JavaFX. In here we are drawing a text “Welcome to Tutorialspoint” and a circle in a scene. To these, we are applying the lighting effect. In here, as we are not mentioning any source, JavaFX uses its default source. Save this code in a file with the name LightingEffectExample.java. import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.effect.Lighting; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.stage.Stage; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; public class LightingEffectExample extends Application { @Override public void start(Stage stage) { //Creating a Text object Text text = new Text(); //Setting font to the text text.setFont(Font.font(null, FontWeight.BOLD, 40)); //setting the position of the text text.setX(60); text.setY(50); //Setting the text to be embedded. text.setText(“Welcome to Tutorialspoint”); //Setting the color of the text text.setFill(Color.RED); //Drawing a Circle Circle circle = new Circle(); //Setting the center of the circle circle.setCenterX(300.0f); circle.setCenterY(160.0f); //Setting the radius of the circle circle.setRadius(100.0f); //setting the fill color of the circle circle.setFill(Color.CORNFLOWERBLUE); //Instantiating the Lighting class Lighting lighting = new Lighting(); //Applying lighting effect to the text text.setEffect(lighting); //Applying lighting effect to the circle circle.setEffect(lighting); //Creating a Group object Group root = new Group(text,circle); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Distant light effect 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 LightingEffectExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls LightingEffectExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – ArcTo Path Object
JavaFX – ArcTo Path Object ”; Previous Next The Path Element Arc is used to draw an arc to a point in the specified coordinates from the current position. It is represented by a class named ArcTo. This class belongs to the package javafx.scene.shape. This class has 4 properties of the double datatype namely − X − The x coordinate of the center of the arc. Y − 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. To draw the Path element arc, you need to pass values to these properties This can be 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 Arc To draw an arc to a specified point from the current position in JavaFX, follow the steps given below. Step 1: Creating a Path Object Create a Path object by instantiating the Path class inside the start() method of Application class as shown below. public class ClassName extends Application { @Override public void start(Stage primaryStage) throws Exception { //Creating a Path object Path path = new Path(); } } Step 2: Create a Path Create the MoveTo path element and set the XY coordinates to the starting point of the line to the coordinates (100, 150). This can be done using the methods setX() and setY() of the class MoveTo as shown below. //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(100.0f); moveTo.setY(150.0f); Step 3: Creating an Object of the Class ArcTo Create the path element quadratic curve by instantiating the class named ArcTo, which belongs to the package javafx.scene.shape as shown below − //Creating an object of the class ArcTo ArcTo arcTo = new ArcTo() Step 4: Setting Properties to the Arc Element Specify the x, y coordinates of the center of the ellipse (of which this arc is a part of). Then you can specify the radiusX, radiusY, start angle, and length of the arc using their respective setter methods as shown below. //setting properties of the path element arc arcTo.setX(300.0); arcTo.setY(50.0); arcTo.setRadiusX(50.0); arcTo.setRadiusY(50.0); Step 5: Adding Elements to the Observable List of Path Class Add the path elements MoveTo and arcTo, created in the previous steps to the observable list of the Path class as follows − //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(cubicCurveTo); Step 6: Launching Application Once the Arc path object is created, follow the given steps below to launch the application properly − Firstly, instantiate the class named Scene by passing the Group object as a parameter value to its constructor. To this constructor, you can also pass dimensions of the application screen as optional parameters. Then, set the title to the stage using the setTitle() method of the Stage class. Now, a Scene object is added to the stage using the setScene() method of the class named Stage. Display the contents of the scene using the method named show(). Lastly, the application is launched with the help of the launch() method. Example Following is a program that draws an arc from the current point to a specified position using the class Path of JavaFX. 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.ArcTo; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; public class ArcExample extends Application { @Override public void start(Stage stage) { //Creating an object of the class Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(250.0); moveTo.setY(250.0); //Instantiating the arcTo class ArcTo arcTo = new ArcTo(); //setting properties of the path element arc arcTo.setX(300.0); arcTo.setY(50.0); arcTo.setRadiusX(50.0); arcTo.setRadiusY(50.0); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(arcTo); //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 an arc through a path”); //Adding scene to the stage stage.setScene(scene); //Displaying the contents of the stage stage.show(); } public static void main(String args[]){ launch(args); } } Compile and execute the saved java file from the command prompt using the following commands. javac –module-path %PATH_TO_FX% –add-modules javafx.controls 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, which is drawn from the current position to the specified point, as shown below. Example Let us try to draw an ArcTo Path in JavaFX to create a pendulum object with a circular pendulum moving to and fro on an Arc Path. Save this code in a file with the name ArcToAnimation.java. import javafx.application.Application; import javafx.animation.PathTransition; import javafx.scene.Group; import javafx.scene.Scene; import javafx.stage.Stage; import javafx.scene.shape.*; import javafx.scene.shape.MoveTo; import javafx.scene.shape.Path; import javafx.util.Duration; public class ArcToAnimation extends Application { @Override public void start(Stage stage) { // Drawing a circle Circle circle = new Circle(300.0f, 50.0f, 40.0f); //Creating an object of the class Path Path path = new Path(); //Moving to the starting point MoveTo moveTo = new MoveTo(); moveTo.setX(250.0); moveTo.setY(250.0); //Instantiating the arcTo class ArcTo arcTo = new ArcTo(); //setting properties of the path element arc arcTo.setX(300.0); arcTo.setY(50.0); arcTo.setRadiusX(50.0); arcTo.setRadiusY(50.0); //Adding the path elements to Observable list of the Path class path.getElements().add(moveTo); path.getElements().add(arcTo); //Creating a path transition PathTransition pathTransition = new PathTransition(); //Setting the duration of the path transition pathTransition.setDuration(Duration.millis(1000)); //Setting the node pathTransition.setNode(circle); //Setting the path pathTransition.setPath(path); //Setting the orientation of the path pathTransition.setOrientation(PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT); //Setting the cycle count for the transition pathTransition.setCycleCount(50); //Setting auto reverse value to true pathTransition.setAutoReverse(true); //Playing the animation pathTransition.play(); //Creating a Group object Group root = new Group(); root.getChildren().addAll(circle, path); //Creating a scene object Scene scene = new Scene(root, 600, 300); //Setting title to the Stage stage.setTitle(“Drawing an arc through a path”); //Adding scene to the stage stage.setScene(scene); //Displaying the
JavaFX – StackPane Layout
JavaFX – Stackpane Layout ”; Previous Next StackPane Layout in JavaFX The StackPane layout serve as a container arranges all the child nodes on top of each other, just like in stack. The node added first is placed at the bottom of the stack and the subsequent nodes are placed on top of it. In the figure below, a StackPane layout is illustrated by the arrangement of three rectangular boxes stacked on top of each other. It shows how much potential of creativity this type of layout holds. The class named StackPane of the package javafx.scene.layout represents the StackPane. This class contains a single property named alignment. This property represents the alignment of the nodes within the stack pane. List of constructors of the StackPane class is as follows − StackPane() − It is the default constructor that constructs an empty StackPane layout with center alignment. StackPane(Node childNodes) − It creates an StackPane layout with specified children nodes and center alignment. In addition to these, this class also provides a method named setMargin(). This method is used to set margin for the node within the stack pane. Example The following program is an example of the StackPane layout. In this, we are inserting a Circle, Sphere and a Text in the same order. Save this code in a file with the name StackPaneExample.java. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.layout.StackPane; import javafx.scene.paint.Color; import javafx.scene.shape.Circle; import javafx.scene.shape.Sphere; import javafx.scene.text.Font; import javafx.scene.text.FontWeight; import javafx.scene.text.Text; import javafx.stage.Stage; public class StackPaneExample extends Application { @Override public void start(Stage stage) { //Drawing a Circle Circle circle = new Circle(300, 135, 100); circle.setFill(Color.DARKSLATEBLUE); circle.setStroke(Color.BLACK); //Drawing Sphere Sphere sphere = new Sphere(50); //Creating a text Text text = new Text(“Hello how are you”); //Setting the font of the text text.setFont(Font.font(null, FontWeight.BOLD, 15)); //Setting the color of the text text.setFill(Color.CRIMSON); //setting the position of the text text.setX(20); text.setY(50); //Creating a Stackpane StackPane stackPane = new StackPane(); //Setting the margin for the circle stackPane.setMargin(circle, new Insets(50, 50, 50, 50)); //Adding all the nodes to the pane stackPane.getChildren().addAll(circle, sphere, text); //Creating a scene object Scene scene = new Scene(stackPane, 400, 300); //Setting title to the Stage stage.setTitle(“Stack Pane 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 StackPaneExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls StackPaneExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;
JavaFX – AnchorPane Layout
JavaFX – Anchorpane Layout ”; Previous Next AnchorPane Layout in JavaFX The Anchor Pane enables the anchoring of child node edges at a specified offset from the anchor pane”s edges. It ensures that nodes maintain a fixed distance from the edge of layout pane. In JavaFX, an anchor pane is represented by a class named AnchorPane which is a part of javafx.scene.layout package. Suppose, we have a node and we need to set an anchor to it from the bounds of the pane in all directions (Top, Bottom, Right and Left). To set an anchor, the AnchorPane class provides four built-in methods namely setBottomAnchor(), setTopAnchor(), setLeftAnchor() and setRightAnchor(). These methods accepts a double value representing the anchor. The following figure illustrates the same − Note that if the anchor pane has a border and/or padding set, the offsets are calculated from the inner edge of these insets. Cosntructors of the AnchorPane class are as follows − AnchorPane() − Constructs an empty AnchorPane layout. AnchorPane(Node childNodes) − It creates a new AnchorPane layout with the specified nodes. Example The following program is an example of the Anchor Pane layout. In this, we are inserting a rotating cylinder in an anchor pane. Save this code in a file with the name AnchorPaneExample.java. import javafx.animation.RotateTransition; import javafx.scene.Scene; import javafx.scene.layout.AnchorPane; import javafx.scene.paint.Color; import javafx.scene.paint.PhongMaterial; import javafx.scene.shape.Cylinder; import javafx.scene.transform.Rotate; import javafx.stage.Stage; import javafx.util.Duration; public class AnchorPaneExample extends Application { @Override public void start(Stage stage) { //Drawing a Cylinder Cylinder cylinder = new Cylinder(); //Setting the properties of the Cylinder cylinder.setHeight(180.0f); cylinder.setRadius(100.0f); //Preparing the phong material of type diffuse color PhongMaterial material = new PhongMaterial(); material.setDiffuseColor(Color.BLANCHEDALMOND); //Setting the diffuse color material to Cylinder5 cylinder.setMaterial(material); //Setting rotation transition for the cylinder RotateTransition rotateTransition = new RotateTransition(); //Setting the duration for the transition rotateTransition.setDuration(Duration.millis(1000)); //Setting the node for the transition rotateTransition.setNode(cylinder); //Setting the axis of the rotation rotateTransition.setAxis(Rotate.X_AXIS); //Setting the angle of the rotation rotateTransition.setByAngle(360); //Setting the cycle count for the transition rotateTransition.setCycleCount(RotateTransition.INDEFINITE); //Setting auto reverse value to false rotateTransition.setAutoReverse(false); //playing the animation rotateTransition.play(); //Creating an Anchor Pane AnchorPane anchorPane = new AnchorPane(); //Setting the anchor to the cylinder AnchorPane.setTopAnchor(cylinder, 50.0); AnchorPane.setLeftAnchor(cylinder, 50.0); AnchorPane.setRightAnchor(cylinder, 50.0); AnchorPane.setBottomAnchor(cylinder, 50.0); //Adding cylinder to the pane anchorPane.getChildren().addAll(cylinder); //Creating a scene object Scene scene = new Scene(anchorPane, 400, 300); //Setting title to the Stage stage.setTitle(“Anchor Pane 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 AnchorPaneExample.java java –module-path %PATH_TO_FX% –add-modules javafx.controls AnchorPaneExample Output On executing, the above program generates a JavaFX window as shown below. Print Page Previous Next Advertisements ”;