Getting Started With JavaFX Technology Using Eclipse IDE
Download completed FirstJavaFXApp Eclipse Project built in this tutorial
Creating Your First JavaFX Application Using Eclipse IDE
This section teaches you how to create your first JavaFX application by using the Eclipse IDE and JavaFX plugin for Eclipse. You create a simple sphere with text. The sphere changes opacity within a specified time period. The application is shown running in the following figure.
Creating the JavaFX Project
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.
- Ensure that your Eclipse IDE already has the JavaFX
plugin for Eclipse software installed. If necessary, revisit the What to Download and Install section.
- Start the Eclipse IDE, if it is not already started. Close the Welcome screen, if it appears.
- Create a new JavaFX project.
- Choose File > New > Project to start the New Project wizard.
- Expand the JavaFX node, select JavaFX Project node, and click Next, as shown in Figure 1.
Figure 1: Selecting JavaFX Project Wizard
- 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
- In the Create a JavaFX Project page, type
FirstJavaFXAppfor 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.
- 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.
- (Optional) If you installed the JavaFX SDK in a non-default location, you might be prompted to set the
JAVAFX_HOMEvariable. 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.
- 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
- Choose File > New > Project to start the New Project wizard.
Adding the Java Package and Main.fx File
- Create the Java package for the project.
- Expand the FirstJavaFXApp folder in the Package Explorer.
The subfolders include the folders for source files and libraries needed by the project.
- Right-click the src folder and select New > Package.
- In the New Java Package dialog box, type
gstutorialin the Name text field and click Finish.
Figure 5: Creating a New Java Package - Create the
Main.fxsource file.
-
Right-click the gstutorial node and select New > Empty JavaFX Script.
- In the New JavaFX Script dialog box, type
Mainin the Name text field and click Finish.
TheMain.fxfile 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.fxFile Created
-
Right-click the gstutorial node and select New > Empty JavaFX Script.
- Add the Stage template.
- In the Snippets window to expand it, click the Applications tab to expand it.
- Select and drag the
Stageobject to the source editor, as shown in Figure 7.
Figure 7: Adding the StageObject
- In the Insert Template dialog box for
Stage, edit thetitle,width, andheightvariables, as shown in Figure 8.
Figure 8: Modifying Stage Template
- Click Insert.
Notice that the Stage code snippet includes the object literalsStageandScene. Theimportstatements for theStageandScenepackages 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 Literal Description StageThe top-level container window required to display any visible JavaFX objects. The default instance variables title,width, andheightdefine the text that appears on the window's top border and the window's height and width. Thescenevariable defines an instance of theSceneobject 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.
Note: For more information, see Using Objects, a lesson in Learning the JavaFX Script Programming Language.
- In the Snippets window to expand it, click the Applications tab to expand it.
- Modify the
Sceneobject to specify the text that you want to appear in the application. You also need to add the import statement for theTextAlignmentclass.
- Add the following import statement at the top of the file, just below where the first
importstatements were defined.
Source Codeimport javafx.scene.text.*;
- Modify the
contentvariable as shown in the following code example. You can copy the lines in bold and paste them into the editor to replace the currentcontentcode block.
Source CodeStage { 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 - Add the following import statement at the top of the file, just below where the first
- Define the basic
Circleobject from which you create the sphere by expanding theBasic Shapessection in the Snippets view and dragging the Circle code snippet in the line above theTextcode block, as shown in the following figure.
Figure 9: Dragging the Circle Code Snippet From the Snippets Window - In the Insert Template dialog box for
Circle, modify the circle'sradiusvariable to have the value of90and click Insert.
The Circle code snippet is added to theMain.fxsource file, along with the necessary import statements for theCircleandColorclasses APIs.
- Place your cursor over the word
Circleto enable theCircleclass 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 - Add a new
RadialGradientsetting to the circle. This gives the circle depth and makes it look more like a sphere.
- At the top of the
Main.fxfile, add the import statements that include the packages containing theRadialGradientandStopclasses used in the code that you are adding. Begin by typing the following line of code.
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.Source Codeimport javafx.scene.paint.
Figure 11: Code Completion for RadialGradientClass - Repeat the previous step for adding the import statements for the
Stopclass, which is also needed to define the radial gradient of the sphere. The following are the import statements that should have been added.
Source Codeimport javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; - Replace the
fillvariable in theMain.fxsource file with the following source code in bold. You can copy the lines in bold, including the closing square brackets and braces for thefillvariable, and paste them into the source editor.
Source CodeStage { 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 - At the top of the
- 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.
- Right-click the FirstJavaFXApp > src > gstutorial > Main.fx node in the Package Explorer and select Run As > JavaFX Application.
- 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 FirstJavaFXAppProject - 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 - Exit the First JavaFX App window and proceed with the rest of the tutorial.
- Right-click the FirstJavaFXApp > src > gstutorial > Main.fx node in the Package Explorer and select Run As > JavaFX Application.
Adding Animation
In this section, you add the opacity and the animation that changes the sphere's opacity.
- In the source editor, add the
opacityvariable at the top of the source file and set its initial value to 1.0, as shown here in bold.
This variable is used in the timeline animation that you create later.Source Codeimport javafx.scene.paint.Color; import javafx.scene.paint.RadialGradient; import javafx.scene.paint.Stop; var opacity = 1.0;
- Add the opacity instance variable to the
Circleobject and bind this instance variable to theopacityglobal variable, as shown in bold in the following code example.
Source CodeCircle { 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
- Expand the Animations section in the Snippets view, select Timeline, and drag the Timeline code snippet to the line just above the
Stagecode block, as shown in the following figure.
Animation occurs along a timeline, represented by a
Figure 14: Dragging Timeline Code Snippet From the Snippets View 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. - In the Insert Template dialog box for Timeline, change the value of the
timeinstance variable from1sto5sand click Insert.
TheTimelineobject literal appears as shown here.
Timeline {
repeatCount: Timeline.INDEFINITE,
keyFrames : [
KeyFrame {
time : 5s,
canSkip: true
} // KeyFrame
] // keyFrames
} // Timeline
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.
- Drag the Animations > Values code clip from the Snippets view to the line just after the
canSkipvariable.
Figure 15: Dragging ValuesCode Clip From the Snippets Window to the Source EditorValuesdefines the list of target variables and the desired values that they should interpolate at the specified time of theKeyFrame.
- In the Insert Template dialog box for Values, change the values of
valuefrom0.0to0.2and the value ofvariabletoopacity.
This code changes the opacity of the sphere.
- Click Insert.
Thevaluesvariable is now as shown here in bold.
The desired value of theSource CodeTimeline { repeatCount: Timeline.INDEFINITE, KeyFrames : [ KeyFrame { time : 5s, canSkip: true values : [ opacity => 0.2 tween Interpolator.LINEAR ] // values } // KeyFrame ] // keyFrames } // Timelineopacityvariable 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, thetweenoperator constructs the interpolated values for the opacity between 1.0 and 0.2 to create the gradual change in the sphere's opacity.
Change the interpolator value fromLINEARtoEASEBOTH.
TheInterpolator.EASEBOTHis the built-in interpolator instance that provides for ease-in and ease-out behavior.
- Add another
KeyFrameinstance to provide a change of opacity from0.2to1.0within the next five-second interval. Copy the secondKeyFramecode block that is shown in bold in the following code example and paste it just below the firstKeyFrameobject as shown next.
Source CodeTimeline { 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
- Add
.play();to the end of theTimelineobject declaration, as shown in bold in the following code example.
Theplay()method plays the timeline as defined. The completedTimelineobject is shown here. - 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.
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();
See Running Your JavaFX Application on the Mobile Emulator to learn how you can run the same application on the JavaFX 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