Getting Started With JavaFX Technology
Download completed FirstJavaFXSphere Project built in this tutorial
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.
- Ensure that you have the NetBeans IDE for JavaFX software already installed on your system. If necessary, revisit the What to Download page.
- Start the NetBeans IDE.
- Create a JavaFX Script Application project.
- Choose File > New Project (Ctrl-Shift-N).
- In the New Project wizard, select JavaFX in the Categories pane and JavaFX Script Application in the Projects pane. Click Next.
- On the Name and Location page, type
FirstJavaFXSpherefor 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.
Figure 1: New Project Wizard With Project Name and Location Specified. - Click Finish.
The FirstJavaFXSphere project opens in both the Projects window and the Files window, and theMain.fxfile opens in the source editor, as shown in Figure 2.
Notice that JavaFX Script code is included within the
Figure 2: FirstJavaFXSphere Project Opened in Projects Window and Main.fxFile in the Source Editor.Main.fxfile 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 StageThe top level container window required to display any visible JavaFX objects. The default instance variables title,widthandheightdefine 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.SceneSimilar to a drawing surface for the graphical content of your application. The sceneinstance variable has acontentvariable that is used to hold JavaFX graphical elements and defines the graphical content of your application. The instance variables,widthandheight, define the width and height of the content area. For more information about theSceneclass, see Presenting UI Objects in a Graphical Scene, a lesson in Building GUI Applications With JavaFX.TextDefines the graphical element that displays text in the scene. FontDefines 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.
- Choose File > New Project (Ctrl-Shift-N).
- 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
TextAlignmentclass.
- Modify the
StageandSceneobject 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.
- Modify the
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
- 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 theMain.fxfile.
import javafx.scene.text.TextAlignment;
- Define the basic Circle object from which you create the sphere by expanding the
Basic Shapessection in the Palette window and dragging the Circle element in the line above theTextcode block, as shown in the following figure.
Figure 3: Drag the Circle Element From the Palette Window.
- 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.
- 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.
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
- 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 theMain.fxfile.
import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop;
- 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.
Figure 4: Sphere in a JavaFX Preview Window.
- The text is black by default. You can change the color of the text to white by using the
fillvariable as shown in the following example.
Text {
font: Font { size: 22 }
x: 20, y: 90
textAlignment: TextAlignment.CENTER
content:"Welcome to \nJavaFX World"
fill: Color.WHITE
}
- Add animation that changes the sphere's opacity.
- Add the
opacityvariable and set its initial value to 1.0.
This variable is used in the timeline animation that you create in later steps.
- Add the
var opacity = 1.0;
Stage {
title: "My First JavaFX Sphere"
width: 300
height: 300
- Add the
opacityinstance variable to theCircleobject and bind this instance variable to theopacityglobal variable as shown in the following code example.
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
}
- 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.
Animation occurs along a timeline, represented by a
Figure 5: Drag Timeline Element From the Palette to the Source Editor.javafx.animation.Timelineobject. Each timeline contains one or more key frames, represented byjavafx.animation.KeyFrameobjects. For more information about animation, see Creating Animated Objects, a lesson in Building GUI Applications With JavaFX. - Change the value of the
timeinstance variable from1sto5sso that now theTimelineobject literal appears as shown below.
Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames : [
KeyFrame {
time : 5s
canSkip: true
} // KeyFrame
] // keyFrames
} // Timeline
- Drag the Animation > Values element from the Palette to the line just after the
timevariable.
Figure 6: Drag Values Element From the Palette to the Source Editor.
Valuesdefine the list of target variables and the desired values they should interpolate at the specified time of the KeyFrame. - Copy the lines shown in bold below and paste them into the source editor to modify the
valuesinstance. This code changes the opacity of the sphere.
-
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.
Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames : [
KeyFrame {
time : 5s
canSkip: true
values : [
opacity => 0.2 tween Interpolator.LINEAR
] // values
} // KeyFrame
] // keyFrames
} // Timeline
- Add another
KeyFrameinstance to provide a gradual change of opacity from 0.2 to 1.0 within the next five-second interval.
-
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.
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
- Add
.play();to the end of the Timeline object declaration, as shown in the following example in bold.
Theplay()method plays the timeline as defined. The completed Timeline object is shown in the following example.
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
- 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. - Add the variables
xandyand set their initial values to 100.0.
These variables are used to bind the position of theCircleobject to the position of the mouse pointer.
var opacity = 1.0;
var x = 100.0;
var y = 100.0;
Timeline {
repeatCount: Timeline.INDEFINITE
keyFrames: [
- Bind the position of the
Circleobject to the variablesxandyas shown in the following code example.
Instead of thecenterXandcenterYvariables, use thetranslateXandtranslateYvariables, which define the X and Y coordinates of the translation that is added to the transformed coordinates of thisCirclenode object. This code ensures that the radial gradient filling is dragged along with the circle.
scene: Scene {
content: [
Circle {
translateX: bind x
translateY: bind y
radius: 90
- Modify the coordinates of the center point for the RadialGradient setting. To get a new value for the
centerXcoordinate, substract the current value oftranslateX, which is 100, from the initial value ofcenterX, which is 75. Thus you obtain -25. Perform a similar calculation for thecenterYcoordinate.
fill: RadialGradient {
centerX: -25
centerY: -25
radius: 90
- 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
Translateclass, selectjavafx.transform.Translate. - Remove the
xandyvariables that specify the coordinates of theTextobject. Add aTranslatetransformation and bind thexandyvariables of theTranslateobject to the global variablesxandyas shown in the following example.
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.
- Modify the
contentvariable of thesceneto group theCircleandTextobjects together as shown in the following example.
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
- 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
Groupclass, selectjavafx.scene.Group.
- Drag the Action > onMouseDragged element from the Palette to the line just before the closing brace for the
Groupobject. - 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.
Figure 7: Drag onMouseDragged Element From the Palette to the Source Editor.
onMouseDragged: function( e: MouseEvent ):Void {
x = e.x;
y = e.y;
}
- Save the code and run the project.
- 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. - 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.
- In the Projects window, right-click the FirstJavaFXSphere project node and select Run Project.
- Add global variables
XandY, which are used in calculations to restrict the dragging of the sphere.
var x = 100.0; var y = 100.0; var X; var Y;
- Drag the Action > onMousePressed element from the Palette to the line just before the
onMouseDraggedfunction. - 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.
onMousePressed: function( e: MouseEvent ):Void {
X = e.sceneX - e.node.translateX;
Y = e.sceneY - e.node.translateY
}
- Here
e.sceneXmeans the X coordinate of a point where the mouse eventeoccurs,e.node.translateXmeans the X coordinate of the upper left point of a node where the mouse eventeoccurs. - Copy the lines shown in bold and paste them into the source editor to modify the
onMouseDraggedfunction.
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;
}
}
}
- Save the code and run the project.
Now the sphere cannot be dragged out of the bounds of the scene.
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.
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 repliesyour information is not used for any other purpose. By submitting a comment, you agree to these Terms of Use.
Cindy Castillo
Technical Writer, Sun Microsystems
Irina Fedortsova
Technical Writer, Sun Microsystems