创建JavaFX项目

Use the steps in this section to create your JavaFX project, which will contain the source file for your first JavaFX application. Note that the screen captures used in this document were taken on a Windows XP system.

  1. Ensure that your Eclipse IDE already has the JavaFX plugin for Eclipse software installed. If necessary, revisit the What to Download and Install section.
  2. Start the Eclipse IDE, if it is not already started. Close the Welcome screen, if it appears.
  3. Create a new JavaFX project.

    1. Choose File > New > Project to start the New Project wizard.
    2. Expand the JavaFX node, select JavaFX Project node, and click Next, as shown in Figure 1.

       

       

      Figure 1: Selecting JavaFX Project Wizard

       

    3. In the Welcome dialog box, as shown in Figure 2, review the information about the anonymous usage data collection and click OK if you agree to participate.

       

       

      Figure 2: Anonymous Usage Data Collection Information

       

    4. In the Create a JavaFX Project page, type FirstJavaFXApp for the Project name, as shown in the next image.

       

       

      Figure 3: Creating a JavaFX Project Wizard

       


      You can create a new project from scratch or from an already existing source, as shown in the Contents section. For this tutorial, leave the default selection for Create new project in workspace.
    5. Leave all other default values unchanged in the Create a JavaFX Project page and click Finish.

      Desktop is the default JavaFX profile used for a new JavaFX project. This profile sets the application to run on the desktop. The Mobile Profile enables you to run the application on a mobile device or the JavaFX Mobile Emulator tool that is bundled with the JavaFX SDK. The system's default Java Runtime Environment (JRE) installation is used for the new JavaFX project that you're creating.
    6. (Optional) If you installed the JavaFX SDK in a non-default location, you might be prompted to set the JAVAFX_HOME variable. Follow the prompts to set this classpath variable. Make sure that you click Folder in the Edit Variable Entry dialog box and navigate to the location of the JavaFX SDK installation folder, for example, javafx-sdk1.2. After that location is set, continue with the next step below.
    7. When prompted to open the JavaFX perspective, click Yes.

      The JavaFX Perspective ensures that the JavaFX Snippets and Outline views are available to you when you are working
      on a JavaFX application.

      The IDE continues with the project creation. The FirstJavaFXApp project opens in the Package Explorer window, as shown in Figure 4. Notice that the Snippets window on the right becomes available after you create the project and subsequently displays JavaFX code snippets that you can use.

       

       

      Figure 4: FirstJavaFXApp Project Opened in Package Explorer

       

Adding the Java Package and Main.fx File

  1. Create the Java package for the project.

    1. Expand the FirstJavaFXApp folder in the Package Explorer.

      The subfolders include the folders for source files and libraries needed by the project.
    2. Right-click the src folder and select New > Package.
    3. In the New Java Package dialog box, type gstutorial in the Name text field and click Finish.

       

      Figure 5: Creating a New Java Package

       

  2. Create the Main.fx source file.

    1. Right-click the gstutorial node and select New > Empty JavaFX Script.
    2. In the New JavaFX Script dialog box, type Main in the Name text field and click Finish.

      The Main.fx file is opened in the source editor area. Notice that the comment block for the author information is initially folded, as shown in Figure 6. Click the icon in the margin area to see how the code-folding feature works. It expands the comment block. You can click the to collapse the comment block again.

       

       

      Figure 6: Main.fx File Created

  3. Add the Stage template.

    1. In the Snippets window to expand it, click the Applications tab to expand it.
    2. Select and drag the Stage object to the source editor, as shown in Figure 7.

       

      Figure 7: Adding the Stage Object

    3. In the Insert Template dialog box for Stage, edit the title, width, and height variables, as shown in Figure 8.

       

      Figure 8: Modifying Stage Template

    4. Click Insert.

      Notice that the Stage code snippet includes the object literals Stage and Scene. The import statements for the Stage and Scene packages were automatically added when the code snippet was inserted. These object literals represent key concepts within the JavaFX application and are described in the following table.

      Table 1: Object Literals Created With Stage Template
      Object LiteralDescription
      StageThe top-level container window required to display any visible JavaFX objects. The default instance variables title, width, and height define the text that appears on the window's top border and the window's height and width. The scene variable defines an instance of the Scene object literal, which sets the area in which you can place the JavaFX objects.
      SceneSimilar to a drawing surface for the graphical content of your application. The scene instance variable has a content variable that is used to hold JavaFX graphical elements and defines the graphical content of your application. The instance variables, width and height, define the width and height of the content area. For more information about the Scene class, see Presenting UI Objects in a Graphical Scene, a lesson in Building GUI Applications With JavaFX.

      Note: For more information, see Using Objects, a lesson in Learning the JavaFX Script Programming Language.


  4. Modify the Scene object to specify the text that you want to appear in the application. You also need to add the import statement for the TextAlignment class.

    1. Add the following import statement at the top of the file, just below where the first import statements were defined.
      Source Code
      import javafx.scene.text.*;
    2. Modify the content variable as shown in the following code example. You can copy the lines in bold and paste them into the editor to replace the current content code block.
      Source Code
      Stage {
           title: "First JavaFX App"
           scene: Scene {
               width: 250
               height: 250
               content: [
                   Text {
                      font: Font { size: 22 }
                      x: 20, y: 90
                     textAlignment: TextAlignment.CENTER
                     content:"Welcome to /nJavaFX  World"
                   }  //Text
               ] // content
           } // Scene 
      } // Stage
  1. Define the basic Circle object from which you create the sphere by expanding the Basic Shapes section in the Snippets view and dragging the Circle code snippet in the line above the Text code block, as shown in the following figure.

     

    Figure 9: Dragging the Circle Code Snippet From the Snippets Window

  2. In the Insert Template dialog box for Circle, modify the circle's radius variable to have the value of 90 and click Insert.

    The Circle code snippet is added to the Main.fx source file, along with the necessary import statements for the Circle and Color classes APIs.
  3. Place your cursor over the word Circle to enable the Circle class API to be displayed in a pop-up window, as shown in the following figure.

    You can click inside the pop-up window to view the entire API documentation for the class. Click anywhere in the source editor to dismiss the API pop-up window.

     

     

    Figure 10: Pop-up API Window

  4. Add a new RadialGradient setting to the circle. This gives the circle depth and makes it look more like a sphere.

    1. At the top of the Main.fx file, add the import statements that include the packages containing the RadialGradient and Stop classes used in the code that you are adding. Begin by typing the following line of code.
      Source Code
      import javafx.scene.paint.
      At the end of the line you just typed, press Ctrl+spacebar to see the code completion pop-up window, as shown in the following figure. Select RadialGradient from the list and press Enter.

      Figure 11: Code Completion for RadialGradient Class

    2. Repeat the previous step for adding the import statements for the Stop class, which is also needed to define the radial gradient of the sphere. The following are the import statements that should have been added.
      Source Code
        import javafx.scene.paint.RadialGradient; 
        import javafx.scene.paint.Stop;
            
    3. Replace the fill variable in the Main.fx source file with the following source code in bold. You can copy the lines in bold, including the closing square brackets and braces for the fill variable, and paste them into the source editor.
      Source Code
        Stage {
          title: "First JavaFX App"
          scene: Scene {
              width: 250
              height: 250
              content: [
                  Circle {
                      centerX: 100, 
                      centerY: 100,
                      radius: 90,
                      fill: RadialGradient {
                              centerX: 75,
                              centerY: 75,
                              radius: 90 
                              proportional: false
                              stops: [
                                  Stop {
                                      offset: 0.0 
                                      color: Color.web("#3B8DED")
                                  },
                                  Stop {
                                      offset: 1.0 
                                      color: Color.web("#044EA4")
                                  }
                              ] // stops
                      } // RadialGradient
                   } // Circle
                   Text {
                     font: Font { size: 22 }
                     x: 20, y: 90
                     textAlignment: TextAlignment.CENTER
                     content:"Welcome to /nJavaFX  World"
                   }  //Text
              ] // content
           } // Scene  
      } // Stage
  5. Save the source code (Ctrl+S on Windows and Cmd+S on Mac) and run the project to see a preview of what you have done so far.

    1. Right-click the FirstJavaFXApp > src > gstutorial > Main.fx node in the Package Explorer and select Run As > JavaFX Application.
    2. In the Edit Configuration dialog box, notice that in the Profile - Target field the default run profile used is Desktop, as shown in Figure 12. Leave Desktop profile -Run as Application as the target run profile.

      You also have the option to run the JavaFX project as an applet, as a Java Web Start application, or as a mobile application by choosing the appropriate Profile - Target option from the drop-down list.

       

      Figure 12: Setting the Run Profile for the FirstJavaFXApp Project

    3. Click Run.

      A new window displays the sphere that you just created, as shown in the following figure.

       

       

      Figure 13: First Run of the JavaFX Sphere

    4. Exit the First JavaFX App window and proceed with the rest of the tutorial.

Adding Animation


In this section, you add the opacity and the animation that changes the sphere's opacity.

 

  1. In the source editor, add the opacity variable at the top of the source file and set its initial value to 1.0, as shown here in bold.
    Source Code
     import javafx.scene.paint.Color;
     import javafx.scene.paint.RadialGradient;
     import javafx.scene.paint.Stop;   
     
     var opacity = 1.0;
    
    This variable is used in the timeline animation that you create later.
  2. Add the opacity instance variable to the Circle object and bind this instance variable to the opacity global variable, as shown in bold in the following code example.
    Source Code
     Circle {
         centerX: 100, 
         centerY: 100,
         radius: 90,
         opacity: bind opacity
         fill: RadialGradient {
             centerX: 75
             centerY: 75
             radius: 90
             proportional: false
             stops: [
                 Stop {
                     offset: 0.0 
                     color: Color.web("#3B8DED")
                 },
                 Stop {
                     offset: 1.0 
                     color: Color.web("#044EA4")
                 }
             ] // stops
         } // RadialGradient
     } //Circle

  3. Expand the Animations section in the Snippets view, select Timeline, and drag the Timeline code snippet to the line just above the Stage code block, as shown in the following figure.

     

    Figure 14: Dragging Timeline Code Snippet From the Snippets View to the Source Editor

    Animation occurs along a timeline, represented by a javafx.animation.Timeline object. Each timeline contains one or more key frames, represented by javafx.animation.KeyFrame objects. For more information about animation, see Creating Animated Objects, a lesson in Building GUI Applications With JavaFX.
  4. In the Insert Template dialog box for Timeline, change the value of the time instance variable from 1s to 5s and click Insert.

    The Timeline object literal appears as shown here.
    Source Code
    Timeline {
        repeatCount: Timeline.INDEFINITE,
        keyFrames : [
            KeyFrame {
                time : 5s,
                canSkip: true
            } // KeyFrame
        ] // keyFrames
    } // Timeline
    
    
    This timeline repeats indefinitely on a five-second interval. The value of the time instance variable, five seconds, defines the elapsed time at which the values within the key frame will be set in a single cycle of the Timeline object. The next couple of steps of this tutorial define those values that will be set.

 

  1. Drag the Animations > Values code clip from the Snippets view to the line just after the canSkip variable.

    Figure 15: Dragging Values Code Clip From the Snippets Window to the Source Editor

    Values defines the list of target variables and the desired values that they should interpolate at the specified time of the KeyFrame.
  2. In the Insert Template dialog box for Values, change the values of value from 0.0 to 0.2 and the value of variable to opacity.

    This code changes the opacity of the sphere.
  3. Click Insert.

    The values variable is now as shown here in bold.
    Source Code
     Timeline {
        repeatCount: Timeline.INDEFINITE,
        KeyFrames : [
                KeyFrame {
                time : 5s,
                canSkip: true
                values : [
                   opacity => 0.2 tween Interpolator.LINEAR
                ] // values
            } // KeyFrame
        ] // keyFrames
    } // Timeline
    
    The desired value of the opacity variable is defined within the five-second interval of the key frame. The => operator provides a literal constructor (a special notation) that makes it easier to express the list of key-interpolated values or object properties.

    In this case, the tween operator constructs the interpolated values for the opacity between 1.0 and 0.2 to create the gradual change in the sphere's opacity.
  4. Change the interpolator value from LINEAR to EASEBOTH.

    The Interpolator.EASEBOTH is the built-in interpolator instance that provides for ease-in and ease-out behavior.
  5. Add another KeyFrame instance to provide a change of opacity from 0.2 to 1.0 within the next five-second interval. Copy the second KeyFrame code block that is shown in bold in the following code example and paste it just below the first KeyFrame object as shown next.
    Source Code
     Timeline {
        repeatCount: Timeline.INDEFINITE,
        keyFrames : [
            KeyFrame {
                time : 5s,
                canSkip: true
                values : [
                   opacity => 0.2 tween Interpolator.EASEBOTH  
                ] // values
            } // KeyFrame
            KeyFrame {
                time : 10s,
                canSkip: true
                values : [
                   opacity => 1.0 tween Interpolator.EASEBOTH  
                ] // values
            } // KeyFrame
        ] // keyFrames
    } // Timeline
    
  1. Add .play(); to the end of the Timeline object declaration, as shown in bold in the following code example.

    The play() method plays the timeline as defined. The completed Timeline object is shown here.
    Source Code
    Timeline {
            repeatCount: Timeline.INDEFINITE,
            keyFrames: [
                KeyFrame {
                    time: 5s,
                    canSkip: true
                    values : [
                        opacity => 0.2 tween Interpolator.EASEBOTH				
                    ] // values
                } // KeyFrame
                KeyFrame {
                    time: 10s,
                    canSkip: true
                    values : [
                        opacity => 1.0 tween Interpolator.EASEBOTH				
                    ] // values
                } // KeyFrame
          ] // keyFrames
    }.play();
    
    
  2. Save the latest changes that you made, select the Main.fx node in the Package Explorer, click the drop-down arrow next to the Run icon  on the main toolbar, and select gstutorial.Main from the list.

    Congratulations! You've just created your first animated JavaFX application.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值