Animate a Circle Drawing Javafx

7 Blitheness and Visual Effects in JavaFX

You lot can use JavaFX to quickly develop applications with rich user experiences. In this Getting Started tutorial, you volition learn to create animated objects and reach complex effects with very petty coding.

Figure 7-1 shows the application to be created.

Figure 7-2 shows the scene graph for the ColorfulCircles application. Nodes that co-operative are instantiations of the Group class, and the nonbranching nodes, too known equally leaf nodes, are instantiations of the Rectangle and Circle classes.

The tool used in this Getting Started tutorial is NetBeans IDE. Before you brainstorm, ensure that the version of NetBeans IDE that you are using supports JavaFX viii. See the Certified System Configurations section of the Java SE Downloads page for details.

Set up the Awarding

Set upwardly your JavaFX project in NetBeans IDE as follows:

  1. From the File menu, choose New Project.

  2. In the JavaFX application category, choose JavaFX Application. Click Next.

  3. Name the project ColorfulCircles and click End.

  4. Delete the import statements that NetBeans IDE generated.

    You tin generate the import statements as you work your way through the tutorial by using either the lawmaking completion characteristic or the Set Imports command from the Source carte in NetBeans IDE. When in that location is a choice of import statements, choose the i that starts with javafx.

Set the Project

Delete the ColorfulCircles course from the source file that NetBeans IDE generated and supervene upon it with the code in Example 7-i.

Case seven-one Basic Awarding

public class ColorfulCircles extends Awarding {       @Override     public void kickoff(Phase primaryStage) {         Group root = new Group();         Scene scene = new Scene(root, 800, 600, Color.BLACK);         primaryStage.setScene(scene);          primaryStage.show();     }    public static void main(Cord[] args) {         launch(args);     } }            

For the ColorfulCircles awarding, it is appropriate to use a group node as the root node for the scene. The size of the group is dictated by the size of the nodes within it. For most applications, notwithstanding, y'all want the nodes to rails the size of the scene and change when the phase is resized. In that case, y'all use a resizable layout node as the root, as described in Creating a Class in JavaFX.

You can compile and run the ColorfulCircles application now, and at each stride of the tutorial, to encounter the intermediate results. If you run into issues, so take a look at the lawmaking in the ColorfulCircles.java file, which is included in the downloadable ColorfulCircles.zip file. At this point, the application is a simple black window.

Add together Graphics

Next, create 30 circles by adding the code in Example seven-2 before the primaryStage.show() line.

Example 7-2 30 Circles

Group circles = new Group(); for (int i = 0; i < 30; i++) {    Circle circle = new Circle(150, Color.web("white", 0.05));    circumvolve.setStrokeType(StrokeType.OUTSIDE);    circle.setStroke(Color.web("white", 0.xvi));    circle.setStrokeWidth(4);    circles.getChildren().add(circle); } root.getChildren().add(circles);            

This code creates a group named circles, then uses a for loop to add 30 circles to the group. Each circle has a radius of 150, fill colour of white, and opacity level of 5 per centum, meaning it is generally transparent.

To create a border around the circles, the code includes the StrokeType grade. A stroke type of OUTSIDE means the boundary of the circle is extended exterior the interior by the StrokeWidth value, which is 4. The colour of the stroke is white, and the opacity level is 16 per centum, making it brighter than the color of the circles.

The final line adds the circles grouping to the root node. This is a temporary construction. Later on, you will modify this scene graph to lucifer the one shown in Figure 7-2.

Figure 7-3 shows the application. Because the lawmaking does not all the same specify a unique location for each circumvolve, the circles are drawn on tiptop of i another, with the upper left-paw corner of the window equally the heart signal for the circles. The opacity of the overlaid circles interacts with the blackness background, producing the grey colour of the circles.

Add a Visual Event

Proceed by applying a box mistiness consequence to the circles so that they appear slightly out of focus. The lawmaking is in Example 7-3. Add this lawmaking before the primaryStage.show() line.

Example 7-3 Box Blur Upshot

circles.setEffect(new BoxBlur(ten, ten, 3));            

This code sets the mistiness radius to ten pixels broad by 10 pixels loftier, and the mistiness iteration to 3, making information technology guess a Gaussian blur. This blurring technique produces a smoothing effect on the border of the circles, as shown in Figure 7-4.

Create a Background Gradient

Now, create a rectangle and fill it with a linear gradient, as shown in Case 7-iv.

Add the lawmaking before the root.getChildren().add(circles) line and then that the gradient rectangle appears behind the circles.

Instance vii-4 Linear Gradient

Rectangle colors = new Rectangle(scene.getWidth(), scene.getHeight(),      new LinearGradient(0f, 1f, 1f, 0f, true, CycleMethod.NO_CYCLE, new           Stop[]{             new Stop(0, Colour.spider web("#f8bd55")),             new Finish(0.fourteen, Colour.web("#c0fe56")),             new Stop(0.28, Color.web("#5dfbc1")),             new Stop(0.43, Color.web("#64c2f8")),             new Stop(0.57, Color.web("#be4af7")),             new Cease(0.71, Color.web("#ed5fc2")),             new Stop(0.85, Color.spider web("#ef504c")),             new Stop(one, Color.web("#f2660f")),})); colors.widthProperty().bind(scene.widthProperty()); colors.heightProperty().demark(scene.heightProperty()); root.getChildren().add(colors);            

This lawmaking creates a rectangle named colors. The rectangle is the same width and height as the scene and is filled with a linear gradient that starts in the lower left-hand corner (0, i) and ends in the upper right-hand corner (ane, 0). The value of true means the slope is proportional to the rectangle, and NO_CYCLE indicates that the color cycle will not repeat. The Stop[] sequence indicates what the slope color should be at a particular spot.

The side by side ii lines of code make the linear gradient adjust as the size of the scene changes by bounden the width and meridian of the rectangle to the width and height of the scene. See Using JavaFX Backdrop and Bindings for more information on binding.

The last line of code adds the colors rectangle to the root node.

The gray circles with the blurry edges now appear on top of a rainbow of colors, every bit shown in Effigy 7-5.

Figure seven-vi shows the intermediate scene graph. At this betoken, the circles grouping and colors rectangle are children of the root node.

Apply a Blend Mode

Next, add color to the circles and darken the scene by adding an overlay alloy result. You volition remove the circles group and the linear gradient rectangle from the scene graph and add together them to the new overlay blend grouping.

  1. Locate the following 2 lines of code:

    root.getChildren().add(colors); root.getChildren().add(circles);              
  2. Replace the 2 lines of code from Step 1 with the lawmaking in Example 7-5.

    Case 7-5 Blend Mode

    Group blendModeGroup =      new Group(new Group(new Rectangle(scene.getWidth(), scene.getHeight(),         Color.Blackness), circles), colors); colors.setBlendMode(BlendMode.OVERLAY); root.getChildren().add(blendModeGroup);                

The grouping blendModeGroup sets up the structure for the overlay alloy. The grouping contains ii children. The first child is a new (unnamed) Group containing a new (unnamed) black rectangle and the previously created circles group. The second child is the previously created colors rectangle.

The setBlendMode() method applies the overlay blend to the colors rectangle. The terminal line of code adds the blendModeGroup to the scene graph equally a child of the root node, as depicted in Figure 7-two.

An overlay alloy is a mutual outcome in graphic design applications. Such a blend tin can darken an image or add highlights or both, depending on the colors in the alloy. In this example, the linear gradient rectangle is used as the overlay. The black rectangle serves to continue the background night, while the nearly transparent circles option up colors from the gradient, just are also darkened.

Figure seven-7 shows the results. Yous will see the total effect of the overlay alloy when y'all breathing the circles in the next step.

Add Animation

The final footstep is to use JavaFX animations to motion the circles:

  1. If you accept not washed so already, add together import static java.lang.Math.random; to the listing of import statements.

  2. Add together the animation lawmaking in Example 7-6 earlier the primaryStage.bear witness() line.

    Example 7-6 Animation

    Timeline timeline = new Timeline(); for (Node circle: circles.getChildren()) {     timeline.getKeyFrames().addAll(         new KeyFrame(Elapsing.ZERO, // prepare start position at 0             new KeyValue(circumvolve.translateXProperty(), random() * 800),             new KeyValue(circle.translateYProperty(), random() * 600)         ),         new KeyFrame(new Duration(40000), // set up stop position at 40s             new KeyValue(circle.translateXProperty(), random() * 800),             new KeyValue(circle.translateYProperty(), random() * 600)         )     ); } // play 40s of blitheness timeline.play();                

Blitheness is driven by a timeline, so this code creates a timeline, then uses a for loop to add together ii key frames to each of the xxx circles. The first key frame at 0 seconds uses the properties translateXProperty and translateYProperty to set up a random position of the circles within the window. The second key frame at xl seconds does the aforementioned. Thus, when the timeline is played, information technology animates all circles from one random position to another over a period of xl seconds.

Effigy 7-viii shows the 30 colorful circles in motion, which completes the application. For the complete source code, see the ColorfulCircles.coffee file, which is included in the downloadable ColorfulCircles.nil file..

Where to Get from Hither

Here are several suggestions about what to practise next:

  • Try the JavaFX samples, which y'all can download from the JDK Demos and Samples section of the Coffee SE Downloads page at http://world wide web.oracle.com/technetwork/java/javase/downloads/. Especially accept a look at the Ensemble application, which provides sample lawmaking for animations and effects.

  • Read Creating Transitions and Timeline Animation in JavaFX. You will notice more than details on timeline animation as well every bit information on fade, path, parallel, and sequential transitions.

  • See Creating Visual Furnishings in JavaFX for additional ways to enhance the look and design of your application, including reflection, lighting, and shadow effects.

  • Try the JavaFX Scene Architect tool to create visually interesting applications. This tool provides a visual layout environment for designing the UI for JavaFX applications and generates FXML code. You tin can use the Properties panel or the Modify option of the menu bar to add together furnishings to the UI elements. See the Properties Console and the Bill of fare Bar sections of the JavaFX Scene Builder User Guide for information.

Close Window

Tabular array of Contents

JavaFX: Getting Started with JavaFX

Expand | Plummet

knoxwasere.blogspot.com

Source: https://docs.oracle.com/javase/8/javafx/get-started-tutorial/animation.htm

0 Response to "Animate a Circle Drawing Javafx"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel