Fifth + start to use javafx2.0

Source: Internet
Author: User
Tags netbeans

This article is from my translation Article http://somefuture.iteye.com/blog/1190880 at javaeye

If you want to use javafx to quickly develop applications with rich user experience, read this article. We will create a simple application and learn how easy it is to implement complex graphics with a small amount of code. Of course, javafx is not just an exceptionally beautiful and vivid shape. After reading this article, it will be helpful to see the sample.

Figure 1 colorful circles Application


Description of "Figure 1 colorful circles application"

If you are familiar with the Graphic Programming Model of the javafx scenario, you can easily understand the program code. Stage is the highest level container of an application, and scene is the drawing surface of the content in the application. The content is organized into scene graphs and is a node Hierarchy Tree.

Figure 2 is an applicationColorfulcircles displays scene graphics.The branch node is
GroupClass instantiation. Non-branch node, that is, leaf node, yesRectangleAnd circleClass instantiation.

Figure 2 colorful circles Scene Graph


Description of "Figure 2 colorful circles scene graph"

Create an application

You can use any tool designed for Java development to build a javafx application. We recommend using netbeans IDE. Before you start, make sure that your Nb version supports javafx2.0. For details, see system requirements.

Install the following steps and use Nb for development:

  1. From the File menu, select new project.

  2. From the javafx Application category, select javafx application and click Next.

  3. Enter project nameColorfulCirclesClick Finish.

  4. Open
    Colorfulcircles. Java file, copy the import declaration and paste it into your project to overwrite the automatically generated statement of Nb.

  5. Alternatively, you can use the Nb Code Completion function or the fix imports command to import the Import Statement. However, make sure that the package starts with javafx.

Create application Basics

Delete the colorfulcircles class generated by netbeans IDE and use
Replace the code in Example 1. The following is the minimum code required to run the javafx application:

Example 1 Basic Application

public class ColorfulCircles extends Application {     public static void main(String[] args) {        launch(args);    }        @Override    public void start(Stage primaryStage) {                primaryStage.show();    }}

Colorfulcircles class inheritedApplicationClass, contains two methods. The first method ismain()Method, used to calllaunch()Method. As javafx best practices,launch()The method is
main()The only method to call.

Then,ColorfulCirclesClass overwrites the abstractstart()Method.start()The parameters of the method are the initial stage of the application. The last line makes the stage visible.

Now you can compile and run colorfulcircles. Remember to check the intermediate result in each step. If something goes wrong, check
Colorfulcircles. Java file.

Add scenario

Now add a scenario for the stage: add three lines of code, see Example 2. There are two best practices: the Code creates a group node for the scenario as the root node, and sets the width and height of the scenario (800 and 600 here ).

InprimaryStage.show()Add the scenario and all its contents before this line. This is another best practice.

Example 2 scene

@Override public void start(Stage primarystage) {    Group root = new Group();    Scene scene = new Scene(root, 800, 600, Color.BLACK);    primaryStage.setScene(scene);    primaryStage.show()

Figure 3 shows the results so far.

Figure 3 stage and scene


Description of "Figure 3 stage and scene"

Add graphics

NextAdded before primarystage. Show ()
The code in Example 3 creates 30 circles.

Example 3 30 Circles

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

These codes are calledcirclesAnd then use an ofr loop to add 30 circles to it. The radius of each circle is 150 and filled with white color. In addition, the opacity is 5%, so it is basically transparent.

Create borders for these circles. The Code containsStrokeTypeClass. Stroke typeOutside indicates that the boundary of the circle is extended.StrokeWidthValue, that is, 4. The stroke color is
whiteThe opacity is 16%, so that it is lighter than the circle color.

The last linecirclesAdd to the root node. This is only a temporary structure. The scene image will be modified later to match
Figure 2 shows that.

Figure 4 shows the current application. Because the Code does not specify a specific position for each circle, they are all superimposed, and the upper left corner of the window is the center of the circle. The opacity of the stacked circle and the effect of the Black Beijing make the circle look gray.

Figure 4 circles


Description of "Figure 4 circles"

Added Visual Effects

Apply the box blur effect to the circle to make them look soft. The code is
Example 4. InprimaryStage.show()Add the code before.

Example 4 box blur effect

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

The Code sets the Blur radius. The width and height are both 10.And iterate three times to make it close to Gaussian blur.In this way, a smooth effect is displayed on the edge of the circle. See figure 5.

Figure 5 box blur on circles


Description of "Figure 5 box blur on circles"

Create background gradient

Create a rectangle and fill it with a linear gradient. For the code, see
Example 5.

Inroot.getChildren().add(circles)Add the code before, so that the rectangle can be under the circle.

Example 5 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, Color.web("#f8bd55")),            new Stop(0.14, Color.web("#c0fe56")),            new Stop(0.28, Color.web("#5dfbc1")),            new Stop(0.43, Color.web("#64c2f8")),            new Stop(0.57, Color.web("#be4af7")),            new Stop(0.71, Color.web("#ed5fc2")),            new Stop(0.85, Color.web("#ef504c")),            new Stop(1, Color.web("#f2660f")),}));root.getChildren().add(colors);

The code is calledColors rectangle.The rectangle is the same as the scene width and height, and the linear gradient is applied from the (0, 0) Point in the lower left corner to the (1, 1) Point in the upper right corner.
true
Indicates that the gradient is proportional to the rectangle,NO_CYCLEIt indicates that the color loop will not be repeated,Stop[]The sequence indicates the gradient color sequence.The last line sets colorsAdd to the root node.

Now the blurred gray circle on the edge appears in the rainbow. See
Figure 6.

Figure 6 linear gradient


Description of "Figure 6 linear gradient"

Figure 7 shows the intermediate scenario diagram. NowcirclesGroupAnd colorsRectangles are children of the root node.

Figure 7 INTERMEDIATE Scene Graph


Description of "Figure 7 INTERMEDIATE scene graph"

Application hybrid mode

Now we can add a color to the circle by adding a mixed coverage effect and make the scene darker. This task requires a little housework and you need to remove it from the scenario.The circles group and the gradient rectangle, and add them to the new hybrid coverage group.

  1. Delete the following two lines of code:

    root.getChildren().add(colors);

    root.getChildren().add(circles);

  2. Add the code in Example 6 to the position where the code is deleted.

    Example 6 Blend Mode

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

     blendModeGroupThe Group creates a structure for the hybrid overwriting group. The group contains two children. The first is a new anonymousGroupContains a new anonymous black rectangle and the previously createdcirclesGroup. The second child was previously created.colorsRectangle.

  3. setBlendMode()Method To apply the hybrid overwrite to the colors rectangle. The last line of codeblendModeGroupThe child added to the scenario as the root node, as shown in figure 2.

The mixed coverage effect is a common effect in the graphic design program. It can obscure images or highlight them, depending on the color in the hybrid group. Here, we use a linear gradient rectangle as the coverage. The black rectangle is used to keep the background dark, and the circle close to the Transparency gets the color from the rectangle, but it is still dimmed.

Figure 8 shows the result. After activating the circle in the next step, you will be able to see the complete mixed coverage effect.

Figure 8 overlay Blend


Description of "Figure 8 overlay blend"

Add an animation

The last step is to use the javafx animation to move the circle:

  1. If you are not ready, addimport static java.lang.Math.random;Import Declaration.

  2. InprimaryStage.show()Previously added the activation code in Example 7.

    Example 7 Animation

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

    The animation is driven by the timeline, so a timeline is created here, and thenforLoop adds two key frames to 30 circles. The first key frame is used at 0 seconds.translateXPropertyAnd translateypropertyAttribute setting a random position in the window. The second key frame is also executed in 40 seconds. In this way, after the timeline play (), all circles will be directed from one random position to the other within 40 seconds.

 

Figure 9 shows 30 circles in motion. View the colorfulcircles. Java file.

Figure 9 animated circles


Description of "Figure 9 animated circles"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.