//rich client /
JavaFX and Swing Integration
Use JavaFX to create visual effects for a more exciting toolbar.
SIMON RITTER
This is the third and final article in a series about integrating
JavaFX with existing Swing applications. In Part 1, we looked at
the basics of wrapping a JavaFX
scene as a JComponent and how
to handle events. In Part 2, we
looked at the use of a JavaFX table
in a sample application. Here,
we’ll use visual effects to create a
more exciting toolbar for the same
sample application, which delivers details about stock quotes.
Note: Download the code for the
sample application here.
The application includes a
toolbar that uses icons to pro-
vide quick access to commands
such as open a portfolio, refresh
stock prices, and create a new
portfolio. This functionality
makes use of the Swing JToolbar
component. To make the toolbar
more visually interesting, we’ll
replace it with the ToolBar con-
trol from JavaFX, retaining all the
same functionality.
The code in Listing 1 simply
takes the name of an image
passed to the constructor and creates an ImageView node that can
be used on the toolbar. We also
need the width of the image for
one of the effects we will produce.
As you can see, we’ve defined four
types of effects that the icon can
have: fade, spin, grow, and slide.
The implementation of these
effects is shown in Listing 2 and
Listing 3, which is also part of
the constructor.
The visual effects change prop-
erties of the icon using a Timeline.
Each of the properties we’re
using is a DoubleProperty, which
we can access via the appropri-
ate method call to the ImageView
object. Once we have a property,
we create a Timeline that has one
KeyFrame at zero seconds and
another KeyFrame at 1,000 ms
(one second). Each KeyFrame uses
KeyValue to define the associated
properties that are to be changed
and the values for the properties
at the given point on the Timeline.
To make the effect continuous,
we set the Timeline to be auto-
reversing and have an indefinite
repeat count. Implicit binding is
used between the icon properties
and the value being changed in
the timeline.
JAVA IN ACTION
Adding Functionality
Let’s start with the JavaFX code
first and then see how we integrate this code into our application. To give the icons more functionality, we’ll create a new class,
ActiveIcon. The outline of the
constructor is shown in Listing 1.
ABOUT US
blog
Simon Ritter provides highlights from his three-part article series on JavaFX and Swing.
PHOTOGRAPH BY BOB ADLER
Constructing the New Toolbar
Using the ActiveIcon class, we
can now construct our toolbar,
as shown in Listing 4. The code
in Listing 4 adds a new method
to the StocksMonitorMain Window
class, which is responsible for
constructing the main GUI. Here,
we use the same technique
described in the first article to