Creating Your First JavaFX Application

This section teaches application developers how to create their first JavaFX application by using the NetBeans IDE for JavaFX technology. For web designers who want to get started using JavaFX Production Suite, see the Getting Started With JavaFX Production Suite article.

In this section, you create a simple sphere with text. The sphere changes opacity within a specified time period. You can also drag the sphere with the mouse. The application is shown in the following figure.



  1. Ensure that you have the NetBeans IDE for JavaFX software already installed on your system. If necessary, revisit the What to Download page.

  2. Start the NetBeans IDE.

  3. Create a JavaFX Script Application project.

    1. Choose File > New Project (Ctrl-Shift-N).

    2. In the New Project wizard, select JavaFX in the Categories pane and JavaFX Script Application in the Projects pane. Click Next.

    3. On the Name and Location page, type FirstJavaFXSphere for the Project Name, specify your desired location for the project's files in the Project Location text field, and leave all other default values unchanged, as shown in Figure 1.

      New Project wizard with project name and location specified. Figure 1: New Project Wizard With Project Name and Location Specified.

    4. Click Finish.

      The FirstJavaFXSphere project opens in both the Projects window and the Files window, and the Main.fx file opens in the source editor, as shown in Figure 2.

      FirstJavaFXSphere Project Opened in Projects Window and <code>Main.fx</code> File  in the Source Editor. Figure 2: FirstJavaFXSphere Project Opened in Projects Window and Main.fx File in the Source Editor.

      Notice that JavaFX Script code is included within the Main.fx file by default. This code includes several import statements and object literals (like Stage). These Object literals represent key concepts within the JavaFX application, and are described in the table below.

      Table 1: Object Literals Created by Default
      Object Literal Description
      Stage The 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 its 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.
      Scene Similar 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.
      Text Defines the graphical element that displays text in the scene.
      Font Defines the font used to display the text in the scene.

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

  4. Modify the Stage object as shown in the following example so that the window has the title. Modify the Scene object to specify both the size of the content area and the text you want to appear in the application. You also need to add the import statement for the TextAlignment class.

    1. Modify the Stage and Scene object literals as shown below. You can copy the lines in bold and paste them into the editor. Notice that an error flag appears. This error is removed in the next step.
Source Code
Stage {
     title: "My First JavaFX Sphere"
     scene: Scene {
         width: 300
         height: 300
         content: [
             Text {
                font: Font { size: 22 }
                x: 20, y: 90
               textAlignment: TextAlignment.CENTER
               content:"Welcome to \nJavaFX  World"

             }  //Text
        ] // content
     } // Scene 

} // Stage

    1. Right-click in any white space in the editor and select Fix Imports (Ctrl+Shift+I) to remove the error flag.

      The following import statement is added to the top of the Main.fx file.
Source Code
import javafx.scene.text.TextAlignment;

  1. Define the basic Circle object from which you create the sphere by expanding the Basic Shapes section in the Palette window and dragging the Circle element in the line above the Text code block, as shown in the following figure.

    Drag the Circle code snippet from the Palette window. Figure 3: Drag the Circle Element From the Palette Window.

  2. Modify the circle's instance variables so that it has the correct size to contain the text. Also, add a new RadialGradient setting, which gives the circle depth and makes it look more like a sphere.

    1. Modify the source file with the following source code in bold. You can copy the lines in bold, including the closing square and curly braces for the fill variable, and paste them into the source editor.
Source Code
Stage {
    title: "My First JavaFX Sphere"
    width: 300
    height: 300

    scene: Scene {
        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
    1. Right-click in any white space in the editor and select Fix Imports (Ctrl+Shift+I) to remove the error flags.

      The following import statements are added to the top of the Main.fx file.
Source Code
import javafx.scene.paint.RadialGradient;
import javafx.scene.paint.Stop;   

  1. Save the code (Ctrl+S) and turn on the Preview feature by clicking the Enable Preview button on the editor toolbar.

    A JavaFX Preview window reveals that the circle you just modified looks more like a sphere, as shown in the following figure. The Preview feature enables you to view the saved state of the GUI design that you are creating.

    Finished JavaFX Sphere Figure 4: Sphere in a JavaFX Preview Window.


  2. The text is black by default. You can change the color of the text to white by using the fill variable as shown in the following example.
Source Code
Text {
    font: Font { size: 22 }
    x: 20, y: 90
    textAlignment: TextAlignment.CENTER
    content:"Welcome to \nJavaFX  World"
    fill: Color.WHITE
}
  1. Add animation that changes the sphere's opacity.

    1. Add the opacity variable and set its initial value to 1.0.

    2. This variable is used in the timeline animation that you create in later steps.

Source Code
var opacity = 1.0; 

Stage {
    title: "My First JavaFX Sphere"
    width: 300
    height: 300
    
    1. Add the opacity instance variable to the Circle object and bind this instance variable to the opacity global variable as shown 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
}
    1. Expand the Animation section in the Palette window, select Timeline, and drag the Timeline element to the line just above the Stage code block, as shown in the following figure.

      Drag Timeline Code Snippet from the Palette to the Source Editor Figure 5: Drag Timeline Element From the Palette 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.

    2. Change the value of the time instance variable from 1s to 5s so that now the Timeline object literal appears as shown below.
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 Animation > Values element from the Palette to the line just after the time variable.

      Drag Values Code Snippet from the Palette to the Source Editor Figure 6: Drag Values Element From the Palette to the Source Editor.

      Values define the list of target variables and the desired values they should interpolate at the specified time of the KeyFrame.

    2. Copy the lines shown in bold below and paste them into the source editor to modify the values instance. This code changes the opacity of the sphere.
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 keyframe. 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, we use the tween operator to construct the interpolated values for the opacity between 1.0 and 0.2 to create the gradual change of sphere's opacity. The Interpolator.LINEAR is the built-in interpolator instance that provides linear time interpolation.
    1. Add another KeyFrame instance to provide a gradual change of opacity from 0.2 to 1.0 within the next five-second interval.
Source Code
Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 5s
            canSkip: true
            values : [
               opacity => 0.2 tween Interpolator.LINEAR
            ] // values
        } // KeyFrame
        KeyFrame {
            time : 10s
            canSkip: true
            values : [
               opacity => 1.0 tween Interpolator.LINEAR
            ] // values
        } // KeyFrame
    ] // keyFrames
} // Timeline

    1. Add .play(); to the end of the Timeline object declaration, as shown in the following example in bold.

      The play() method plays the timeline as defined. The completed Timeline object is shown in the following example.
Source Code
Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames : [
        KeyFrame {
            time : 5s
            canSkip : true
            values : [
            opacity => 0.2 tween Interpolator.LINEAR
            ]//values
        }//KeyFrame
        KeyFrame {
            time : 10s
            canSkip : true
            values : [
            opacity => 1.0 tween Interpolator.LINEAR
            ]//values
        }//KeyFrame
    ]
}.play(); //Timeline

  1. Add a dragging behavior to the sphere with the text.

    Note that the position of graphical objects in your application is specified by using absolute coordinates. To provide the dragging behavior, you should change the code so that objects' coordinates depend on the position of the mouse pointer.

    Note also that the sphere should be dragged along with both its RadialGradient setting and the text. Whenever you need to provide similar behavior for several objects, you should group these objects and implement the behavior for the whole group.

    1. Add the variables x and y and set their initial values to 100.0.

      These variables are used to bind the position of the Circle object to the position of the mouse pointer.
Source Code
var opacity = 1.0;
var x = 100.0;
var y = 100.0;

Timeline {
    repeatCount: Timeline.INDEFINITE
    keyFrames: [

    1. Bind the position of the Circle object to the variables x and y as shown in the following code example.

      Instead of the centerX and centerY variables, use the translateX and translateY variables, which define the X and Y coordinates of the translation that is added to the transformed coordinates of this Circle node object. This code ensures that the radial gradient filling is dragged along with the circle.
Source Code
scene: Scene {
    content: [
       Circle {
           translateX: bind x
           translateY: bind y

           radius: 90

    1. Modify the coordinates of the center point for the RadialGradient setting. To get a new value for the centerX coordinate, substract the current value of translateX, which is 100, from the initial value of centerX, which is 75. Thus you obtain -25. Perform a similar calculation for the centerY coordinate.
Source Code
fill: RadialGradient {
    centerX: -25
    centerY: -25
    radius: 90
    

    1. Right-click in any white space in the editor and select Fix Imports (Ctrl+Shift+I) to remove the error flag. To fix the import for the Translate class, select javafx.transform.Translate.

    2. Remove the x and y variables that specify the coordinates of the Text object. Add a Translate transformation and bind the x and y variables of the Translate object to the global variables x and y as shown in the following example.
Source Code
Text {
    font: Font { size: 22 }
    textAlignment: TextAlignment.CENTER
    content:"Welcome to \nJavaFX  World"
    fill: Color.WHITE
    transforms: [
        Translate{
            x: bind x - 76
            y: bind y - 10
        }
    ]
}
    Save the code and check in the JavaFX Preview Window that the modified application looks the same.

    1. Modify the content variable of the scene to group the Circle and Text objects together as shown in the following example.
Source Code
scene: Scene {
    width: 300
    height: 300
    content: Group {
        content: [
            Circle {
                translateX: bind x
                translateY: bind y
                radius: 90
                opacity: bind opacity
                fill: RadialGradient {
                    centerX: -25
                    centerY: -25
                    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 }
                 textAlignment: TextAlignment.CENTER
                 content:"Welcome to \nJavaFX  World"
                 fill: Color.WHITE
                 transforms: [
                     Translate{
                         x: bind x - 76
                         y: bind y - 10
                     }
                 ]
             }  //Text
        ] // content
    } //Group
} // Scene
    1. Right-click in any white space in the editor and select Fix Imports (Ctrl+Shift+I) to remove the error flag. To fix the import for the Group class, select javafx.scene.Group.

    2. Drag the Action > onMouseDragged element from the Palette to the line just before the closing brace for the Group object.

    Drag Values Code Snippet from the Palette to the Source Editor Figure 7: Drag onMouseDragged Element From the Palette to the Source Editor.

    1. Copy the lines shown in bold below and paste them into the source editor to define the function that will be called if a mouse-dragged event occurs.
Source Code
onMouseDragged: function( e: MouseEvent ):Void {
x = e.x;
y = e.y;
}

  1. Save the code and run the project.

    1. In the Projects window, right-click the FirstJavaFXSphere project node and select Run Project.

      The IDE compiles the project and prepares the files necessary to run the application using the standard execution model. When the project is compiled successfully, a sphere that changes its opacity is displayed.

    2. Drag the sphere with the mouse pointer. Notice that you can drag the sphere out of the bounds of the application window. In the next step, you improve the dragging behavior so that the sphere never disappears.
  1. Add global variables X and Y, which are used in calculations to restrict the dragging of the sphere.
Source Code
var x = 100.0;
var y = 100.0;
var X;
var Y;

    1. Drag the Action > onMousePressed element from the Palette to the line just before the onMouseDragged function.

    2. Copy the lines shown in bold and paste them into the source editor to define the function that will be called if a mouse-pressed event occurs.
Source Code
onMousePressed: function( e: MouseEvent ):Void {
    X = e.sceneX - e.node.translateX;
    Y = e.sceneY - e.node.translateY
}
    1. Here e.sceneX means the X coordinate of a point where the mouse event e occurs, e.node.translateX means the X coordinate of the upper left point of a node where the mouse event e occurs.
    2. Copy the lines shown in bold and paste them into the source editor to modify the onMouseDragged function.
Source Code
onMouseDragged: function( e: MouseEvent ):Void {
   if (e.sceneX - X <0) {
        e.node.translateX = 0;
    } else { if (e.sceneX - X > 280 - e.node.boundsInLocal.width){
           e.node.translateX = 280 - e.node.boundsInLocal.width;
    } else {
           e.node.translateX = e.sceneX - X;
    }
    }
    if (e.sceneY - Y <0) {
        e.node.translateY = 0;
    } else {if (e.sceneY - Y > 280 - e.node.boundsInLocal.height){
           e.node.translateY = 280 - e.node.boundsInLocal.height;
    } else{
         e.node.translateY = e.sceneY - Y;
    }
    }
}
  1. Save the code and run the project.

    Now the sphere cannot be dragged out of the bounds of the scene.

  2. Congratulations! You've just created your first JavaFX application.

See Running Your JavaFX Application on the Mobile Emulator to learn how you can run the same code on the Mobile Emulator, Working With JavaFX Samples for samples from which you can learn more about the JavaFX Script language, and the Learning More About JavaFX page for additional resources.


Rate This Article
Comments

Do you have comments about this document? We welcome your participation in our community. Please keep your comments civil and on point. You may optionally provide your email address to be notified of replies—your information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.

 

English
日本語
한국어
简体中文
русский
Português do Brasil