www.it-ebooks.info
™
JavaFX
Developer’s Guide
www.it-ebooks.info
™
JavaFX
Developer’s Guide
Kim Topley
Upper Saddle River, NJ • Boston • Indianapolis • San Francisco
New York • Toronto • Montreal • London • Munich • Paris • Madrid
Capetown • Sydney • Tokyo • Singapore • Mexico City
www.it-ebooks.info
JavaFX™ Developer’s Guide
Acquisitions Editor
Greg Doench
Copyright © 2011 by Pearson Education, Inc.
All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or
transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise,
without written permission from the publisher. No patent liability is assumed with respect to
the use of the information contained herein. Although every precaution has been taken in
the preparation of this book, the publisher and author assume no responsibility for errors or
omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein.
Library of Congress Cataloging-in-Publication Data
Topley, Kim.
JavaFX developer’s guide / Kim Topley.
p. cm.
Includes bibliographical references and index.
ISBN 978-0-321-60165-0 (pbk. : alk. paper) 1. Java (Computer program language) 2.
JavaFX (Electronic resource) 3. Graphical user interfaces (Computer systems) 4.
Application software—Development. 5. Internet programming. I. Title.
QA76.73.J38T693 2010
005.13’3—dc22
2010010696
Development
Editor
Michael Thurston
Managing Editor
John Fuller
Full-Service
Production
Manager
Julie B. Nahil
Copy Editor
Keith Cline
Indexer
Rebecca Salerno
Proofreader
Apostrophe
Editing Services
Publishing
Coordinator
Michelle Housley
Text printed in the United States on recycled paper at Edwards Brothers in Ann Arbor,
Michigan.
First Printing, October 2010
Book Designer
Gary Adair
ISBN 13: 978-0-321-60165-0
ISBN 10:
0-321-60165-3
Composition
Jake McFarland
Trademarks
All terms mentioned in this book that are known to be trademarks or service marks have
been appropriately capitalized. Pearson cannot attest to the accuracy of this information.
Use of a term in this book should not be regarded as affecting the validity of any trademark
or service mark.
Warning and Disclaimer
Every effort has been made to make this book as complete and as accurate as possible,
but no warranty or fitness is implied. The information provided is on an “as is” basis. The
author and the publisher shall have neither liability nor responsibility to any person or entity
with respect to any loss or damages arising from the information contained in this book.
Bulk Sales
Pearson offers excellent discounts on this book when ordered in quantity for bulk
purchases or special sales. For more information, please contact U.S. Corporate and
Government Sales, 1-800-382-3419,
For sales outside of the United States, please contact: International Sales,
Visit us on the web: informit.com/aw
For information regarding permissions, write to: Pearson Education, Inc., Rights and
Contracts Department, 501 Boylston Street, Suite 900, Boston, MA, 02116;
Fax: (617) 671-3447.
www.it-ebooks.info
Download from www.wowebook.com
❖
For the D in KADMAS,
the center of my universe.
❖
www.it-ebooks.info
Download from www.wowebook.com
Contents at a Glance
About the Author
Preface
xxv
xxvi
I: Introduction to JavaFX
1 An Overview of JavaFX 3
2 JavaFX Script Basics 17
3 JavaFX Script Development 33
4 A Simple JavaFX Application 45
II: The JavaFX Script Language
5 Variables and Data Types
89
6 Expressions, Functions, and Object Literals
7 Sequences
153
8 Controlling Program Flow
9 Binding
195
10 Triggers
221
11 JavaFX Script Classes
12 Platform APIs
13 Reflection
121
179
239
285
309
III: User Interfaces with JavaFX
14 User Interface Basics
341
15 Node Variables and Events
16 Shapes, Text, and Images
375
433
17 Coordinates, Transforms, and Layout
18 Animation
503
591
19 Video and Audio
627
www.it-ebooks.info
Download from www.wowebook.com
Contents at a Glance
20 Effects and Blending
21 Importing Graphics
651
703
22 Cross-Platform Controls
23 Style Sheets
737
811
24 Using Swing Controls
829
25 Building Custom Controls
26 Charts
vii
865
911
IV: Miscellaneous
27 Using External Data Sources
28 Packaging and Deployment
949
1025
A Using JavaFX Command-Line Tools
B CSS Properties
Index
1049
1061
1071
www.it-ebooks.info
Download from www.wowebook.com
Table of Contents
About the Author
Preface
xxv
xxvi
I: Introduction to JavaFX
1 An Overview of JavaFX
The JavaFX Platform
3
3
The JavaFX Script Language
Variable Declarations
Access to Java APIs
Object Literals
Binding
5
6
6
7
8
Scripts and Compilation
The JavaFX Runtime
8
9
User Interface Classes
Video and Audio
Animation
9
10
10
Network Access
12
JavaFX Development Tools
Deployment
13
14
Java Platform Dependencies and Installation
The Java Plug-In
14
15
Converting an Applet to an Installed Application
2 JavaFX Script Basics
Source File Structure
Comments
15
17
17
18
Single-Line Comments
Multiline Comments
18
18
Documentation Comments
The package Statement
20
The import Statement
Import by Name
20
20
Wildcard Imports
Static Imports
19
21
21
Automatic Imports
22
www.it-ebooks.info
Download from www.wowebook.com
Contents
Direct Class References
Other JavaFX Statements
23
23
Variable Declarations
23
Value Assignment and Data Manipulation
Using Java Methods
24
Binding Expressions
24
Functions
23
25
Flow-of-Control Statements
Class Definitions
Triggers
ix
26
26
26
JavaFX Keywords and Reserved Words
Script Execution and Arguments
Predefined Variables
27
28
31
3 JavaFX Script Development
33
Compiling and Running JavaFX Code
33
Development Using the NetBeans IDE
Development with the Eclipse IDE
34
39
Documentation in JavaFX Source Code
43
Viewing JavaFX Documentation in NetBeans
Viewing JavaFX Documentation in Eclipse
4 A Simple JavaFX Application
45
Building the SnowStorm Application
Creating the SnowStorm Project
Building the User Interface
Adding the Animation
43
44
46
46
47
58
Counting the Snowflakes
64
SnowStorm on the Web, a Phone, and TV
65
Running SnowStorm Using Java Web Start
Running SnowStorm as an Applet
65
67
Running SnowStorm on the Mobile Emulator
70
Running SnowStorm on the JavaFX TV Emulator
Debugging the SnowStorm Application
Setting Breakpoints
72
The Call Stack View
73
Inspecting Variables
73
72
72
www.it-ebooks.info
Download from www.wowebook.com
x
Contents
Changing Variable Values
74
Stepping Through Code
75
Disabling and Removing Breakpoints and Resuming
Execution 76
Profiling the SnowStorm Application
Using the NetBeans Profiler
77
77
Source Code for the SnowStorm Application
82
II: The JavaFX Script Language
5 Variables and Data Types
Variable Declarations
89
89
Declaring Variables with var
89
Declaring Variables with def
92
Variable Scopes
Object Types
93
94
Creating a JavaFX Object Instance
Invoking JavaFX Functions
Accessing Variables
95
96
Using Java Classes in JavaFX Code
Basic Data Types
97
Numeric Types
97
The Boolean Type
The String Type
97
102
103
String Localization
Type Inference
95
108
117
Visibility of Variables
119
6 Expressions, Functions, and Object Literals
Expressions and Operations
121
Numeric Operations
123
Boolean Operations
129
Object and Class Operations
JavaFX Functions
121
130
134
Declaring Functions
134
Functions and Variables
137
Functions Within Functions
138
www.it-ebooks.info
Download from www.wowebook.com
Contents
Invoking JavaFX Functions
Invoking Java Methods
Function Variables
138
138
139
Anonymous Functions
145
Visibility of Functions
147
Object Literals
147
Initializing a JavaFX Object
148
Variables in Object Literals
149
Functions in Object Literals
150
7 Sequences
153
Sequence Creation
153
The String Form of a Sequence
Range Notation
155
156
Sequence Equality and Copying
Querying Sequences
157
158
Obtaining the Size of a Sequence
158
Obtaining an Element of a Sequence
Obtaining Part of a Sequence
159
160
Querying a Sequence by Condition
Modifying Sequences
160
162
Replacing Elements
Inserting Elements
162
163
Removing Elements
165
Replacing a Range of Elements
Operations on Sequences
167
Comparing Sequences
167
Searching for Elements
166
168
Finding the Largest and Smallest Elements
Sorting a Sequence
Shuffling a Sequence
172
174
174
Array Variable Declaration
174
Array Variable Initialization
175
Array Operations
Array Size
169
171
Searching and Updating a Sorted Sequence
Java Arrays
xi
176
177
www.it-ebooks.info
Download from www.wowebook.com
xii
Contents
8 Controlling Program Flow
The if Statement
179
179
The while Statement
181
The break Statement
182
The continue statement
The for Statement
184
184
Iterating over a Sequence
184
The for Statement as an Expression
186
Iterating over a Subset of a Sequence
Iterating over Multiple Sequences
Iterating over an Iterable
Iterating over an Array
Exception Handling
9 Binding
187
188
190
193
193
195
Binding to Variables and Expressions
Binding to a Script Variable
Binding in an Object Literal
Binding to an Expression
195
195
196
199
Binding and the def Statement
201
Binding to an Instance Variable
201
Binding with a Conditional Expression
Bidirectional Binding
Eager and Lazy Binding
Binding and Functions
202
203
206
207
Binding and Unbound Functions
Binding and Bound Functions
207
209
Optimization of Bound Function Evaluation
Content of a Bound Function
Binding and Sequences
Binding to a Sequence
212
213
217
217
Binding to a Transformed Sequence
Binding to the Size of a Sequence
218
219
Binding to a Range of Sequence Elements
219
www.it-ebooks.info
Download from www.wowebook.com
Contents
10 Triggers
221
Triggers on Simple Variables
Declaring a Trigger
221
221
Getting the Previous Value
Triggers and Binding
223
223
Using a Trigger to Enforce Constraints
Triggers and Sequences
224
229
Replacing Elements in a Sequence
230
Removing Elements from a Sequence
231
Inserting Elements into a Sequence
233
Example Use of a Sequence Trigger
234
Triggers and Instance Variables
11 JavaFX Script Classes
240
An Example JavaFX Class
Class Visibility
236
239
JavaFX Class Declaration
241
242
Instance Variables
243
Instance Functions
246
Subclassing and Abstract Classes
An Abstract Base Class
Function Overloading
Function Overriding
249
249
Extending the Base Class
251
253
254
Function Selection by Classname
Using Bound Functions
259
Class Initialization
261
Initialization Order
258
258
Variable Overrides
261
Using the init and postinit Blocks
Classes and Script Files
Mixins
xiii
263
265
266
Implementing Logging with a Mixin
Mixin Characteristics
272
Mixins and Inheritance
Mixins and Triggers
267
273
280
Initialization and Mixins
281
www.it-ebooks.info
Download from www.wowebook.com
xiv
Contents
12 Platform APIs
285
Built-In Functions
285
Writing to the System Output Stream
Object Comparison
Arguments and System Properties
Application Arguments
288
System Properties
290
Application Shutdown
287
287
Named Arguments
Deferring Operations
286
286
292
294
Functions for Internationalization
295
Changing String Localization Defaults
Local Storage
296
298
Reading and Writing Data
Storage Metadata
Removing Data
299
301
303
Resource Names and Access Control
Conditional Features
13 Reflection
309
Context and Classes
309
The Reflection Context
309
Reflective Access to Classes
Types and Values
310
314
Representation of Types
Values
305
307
314
317
Variables and Functions
320
Reflecting on Variables
322
Reflecting on Functions
323
Filtered Searches
326
Reflecting on Variables and Functions
Using Reflection
327
328
Creating Class Instances: Part 1
328
Reading and Setting Variable Values
Invoking Functions
328
330
Creating and Accessing Sequences
Creating Class Instances: Part 2
333
336
www.it-ebooks.info
Download from www.wowebook.com
Contents
xv
III: User Interfaces with JavaFX
14 User Interface Basics
The Stage Class
341
342
Stage Appearance and State
Stage Position and Size
Style and Opacity
Extensions
354
357
The Scene Class
Nodes
358
360
Node Organization
Events
367
Colors
367
Effects
368
Alerts
342
348
361
369
Information Alert
Confirm Alert
370
Question Alert
3D Features
369
371
372
Cameras and the Z-Axis of the Scene Graph
15 Node Variables and Events
Cursors
Colors
375
375
378
Solid Colors
379
Linear Gradients
383
Radial Gradients
392
Events
401
Mouse Events
401
The Mouse and the MouseEvent Class
Keyboard Events
433
433
Basic Shapes
Paths
403
425
16 Shapes, Text, and Images
Shapes
372
434
451
SVGPath
456
Stroking and Filling Shapes
456
www.it-ebooks.info
Download from www.wowebook.com
xvi
Contents
Stroking Shapes
Shape Filling
456
463
The Text Class
466
Text Content and Positioning
Text Fill and Stroke
Text Decoration
Fonts
466
470
471
472
Font Characteristics
473
Physical and Logical Fonts
The Font Class
476
477
Listing Fonts and Font Families
Selecting Fonts
479
Groups and Custom Nodes
Images
479
482
486
Loading an Image
486
Displaying an Image
497
17 Coordinates, Transforms, and Layout
Transforms
Translation
Rotation
Scaling
503
503
506
508
511
Shearing
515
Combining Transforms
Transform Order
517
517
Combining Transforms and Node
Variable Settings 521
Clipping
523
Coordinates and Bounds
527
Getting Node Bounds
527
Coordinate System Conversions
Node Layout
537
538
Node Sizes and Layout
The Flow Container
The Stack Container
539
547
555
The HBox and VBox Containers
559
www.it-ebooks.info
Download from www.wowebook.com
Contents
The Tile Container
563
The Panel Container
572
The ClipView Node
Centering Nodes
574
577
SnowStorm Revisited
579
Placing the Background Image
581
Placing and Animating the Snow
Coordinates and Screens
Using Two Screens
585
588
Changing Screen Arrangement
Timelines
582
585
Discovering Screens
18 Animation
xvii
589
591
591
Time Literals and the Duration Class
Key Frames
595
596
Interpolation and Interpolators
Controlling a Timeline
600
605
Repeating an Animation
605
Automatically Reversing an Animation
607
Pausing, Stopping, and Restarting an Animation
608
Changing the Speed and Direction of an
Animation 609
Starting a Timeline from the End
Using a Timeline as a Timer
Animation Length
Transitions
610
611
613
613
The Transition Class
TranslateTransition
RotateTransition
ScaleTransition
614
616
617
FadeTransition
618
PathTransition
619
PauseTransition
613
622
Sequential and Parallel Transitions
622
www.it-ebooks.info
Download from www.wowebook.com
xviii
Contents
19 Video and Audio
The Media Class
627
628
The MediaPlayer Class
630
Controlling Media Playback
630
Restricting and Repeating Playback
Volume Control
632
633
Monitoring Playback
634
Synchronizing External Events with Playback
The MediaView Class
639
Size and Position of the Video Frame
The Viewport
20 Effects and Blending
Effects Overview
646
651
651
Effects Chains
651
Effects and Nodes
652
Effects and Groups
655
The JavaFX Effects Classes
GaussianBlur
656
659
DropShadow
660
InnerShadow
663
Shadow
Glow
664
665
666
Identity
Flood
656
657
MotionBlur
Bloom
640
644
Transforms and Effects
BoxBlur
637
667
669
ColorAdjust
669
InvertMask
671
Reflection
671
SepiaTone
673
PerspectiveTransform
DisplacementMap
673
679
www.it-ebooks.info
Download from www.wowebook.com
Contents
Blending
686
The Blend Effect
686
The Group Blend Mode
Lighting
xix
688
690
The surfaceScale Variable
The Bump Map
DistantLight
692
693
694
PointLight
697
SpotLight
698
21 Importing Graphics
703
The JavaFX Production Suite
703
Using Adobe Illustrator and Photoshop Graphics
Exporting Graphics from Adobe Illustrator
Previewing the JavaFX Format Files
705
708
Loading Graphics into a JavaFX Application
Specifying Animation Paths with Illustrator
Embedding Fonts
705
710
717
720
Embedding Images
724
Using a Stub Node
725
Creating Multiple Copies of a Graphics Element
Importing SVG Graphics
733
22 Cross-Platform Controls
Controls Overview
737
The Label Control
738
737
Label and the Labeled Class
Basic Labels
739
741
Positioning of Text and Graphics
Multiline Text
742
746
Text Overruns and Wrapping
Button Controls
731
747
749
The Button Class
749
The Hyperlink Class
752
The ToggleButton, RadioButton, and
CheckBox Classes
756
www.it-ebooks.info
Download from www.wowebook.com
xx
Contents
The TextBox Control
TextBox Width
761
764
TextBox Height
Editability
764
764
Setting and Getting the Content of the TextBox
Selection
766
769
Copy and Paste
771
The PasswordBox Control
The ListView Control
771
773
Creating a ListView
ListView Selection
773
778
ListView Cell Rendering
The ChoiceBox Control
The ScrollBar Control
782
786
787
ScrollBar Value and Range
User Gestures
789
Using the ScrollBar Control
The ScrollView Control
Scrollable Node Size
797
797
797
Basic Slider Operation
Tick Marks
790
794
Scrollbar Display and Values
The Slider Control
789
798
800
The ProgressIndicator and ProgressBar Controls
804
Using the ProgressBar and ProgressIndicator
Controls 804
The Separator Control
Tooltips
807
808
23 Style Sheets
811
Style Sheet Basics
811
Using a Style Sheet
Style Sheet Structure
Selection by ID
812
813
814
Style Sheet Property Specifications
Fonts
824
824
www.it-ebooks.info
Download from www.wowebook.com
Contents
Paints
826
Effects
828
24 Using Swing Controls
829
Swing Component Wrappers
829
SwingComponent Variables
830
SwingComponent as a Node
830
Accessing the Wrapped Swing Component
Labels
832
833
Text and Icon
834
Positioning the Content of SwingLabel
Text Input
836
839
Configuring the SwingTextField Control
Handling Input
Buttons
xxi
840
842
843
The SwingAbstractButton and SwingButton
Classes 843
Toggle Buttons
846
Radio Buttons and Check Boxes
The SwingList Class
848
849
Creating a SwingList Control
Handling the Selection
850
852
The SwingScrollPane Class
852
The SwingComboBox Class
854
Using a Noneditable SwingComboBox
Using an Editable SwingComboBox
The SwingSlider Class
857
Using Other Swing Components
860
Using a Generic JavaFX Wrapper
Creating a JavaFX Wrapper Class
25 Building Custom Controls
Custom Nodes
855
856
860
862
865
865
The CoordinateGrid Node
Custom Containers
866
869
A Border Container
869
Using the Panel Class
884
www.it-ebooks.info
Download from www.wowebook.com
xxii
Contents
Custom Controls
887
Custom Control Architecture
887
Control Appearance and Styling
890
A Skeleton Custom Control
890
A Media Player Control Bar
895
26 Charts
911
Chart Basics
911
Chart Components
Chart Data
914
Chart Interaction
Pie Charts
912
914
914
Creating a Pie Chart
A 3D Pie Chart
914
916
Customizing a Pie Chart
Bar Charts
917
919
Creating a Bar Chart
A 3D Bar Chart
919
922
Bar Chart Customization
Line Charts
922
926
Creating a Line Chart
926
Line Chart Customization
Area Charts
928
930
Scatter Charts
932
Bubble Charts
934
Chart Interaction
936
Common Customizations
Chart Customization
937
937
XY Chart Customization
Axis Customization
939
941
IV: Miscellaneous
27 Using External Data Sources
The HttpRequest Class
949
950
Basic Use of the HttpRequest Class
Lifecycle of an HTTP Request
GET Requests
950
952
955
www.it-ebooks.info
Download from www.wowebook.com
Contents
PUT Requests
965
POST Requests
971
DELETE Requests
973
Using RESTful Web Services
Parsing XML
974
975
A Twitter Web Service Client
A JSON Web Service Client
RSS and Atom Feeds
Feeds Overview
RSS Feeds
Atom Feeds
xxiii
983
988
995
996
997
1004
Tasks and Progress Monitoring
Task State Variables
1009
Progress Monitoring
1010
A State Monitoring Example
1008
1011
Asynchronous Operations and Database Access
A Database Access Task
1014
1015
Implementing the Database Access Task
28 Packaging and Deployment
1018
1025
Packaging and Deployment for the Desktop
1026
Creating a Packaged Application and Applet
with javafxpackager 1026
Application Deployment
Applet Deployment
1029
1033
Setting and Reading Parameters
Incorporating Libraries
1037
1039
Compressing the JAR Files
1042
Signing Applications and Applets
1043
Packaging and Deployment for Mobile Devices
Creating a Packaged Mobile Application
Deployment
1045
1046
1047
A Using JavaFX Command-Line Tools
1049
Development Using Command-Line Tools
Compiling a JavaFX Application
Running a JavaFX Application
1049
1050
1051
Development Using an Ant Script
1052
Generating Documentation from JavaFX Source
1055
www.it-ebooks.info
Download from www.wowebook.com
xxiv
Contents
B CSS Properties
1061
Properties Applicable to Nodes
Group Properties
1062
ImageView Properties
Text Properties
1061
1062
1062
Properties Applicable to Shapes
ClipView Properties
1063
1064
Rectangle Properties
1064
Properties Applicable to Containers
Flow Properties
HBox Properties
1065
Stack Properties
1065
Tile Properties
VBox Properties
1064
1065
1066
1066
Properties Applicable to Controls
1067
Properties Applicable to Labeled Nodes
ListView Properties
1068
ScrollBar Properties
1068
ScrollView Properties
1069
Separator Properties
1069
Slider Properties
1069
TextBox and PasswordBox Properties
Index
1067
1070
1071
www.it-ebooks.info
Download from www.wowebook.com
About the Author
Kim Topley is a freelance computer consultant, based in England. He has worked in the
computer industry for 30 years, writing microcode for mainframe computers, device
drivers, file systems, and security features for the UNIX operating system, communications protocol stacks for Cray supercomputers, and C and Java applications for financial
institutions. He learned Java as a result of a chance encounter with the book Core Java in
a bookshop in 1995 and has written four Java books—Core JFC and Core Swing:
Advanced Programming, both published by Prentice Hall, and J2ME in a Nutshell and Java
Web Services in a Nutshell for O’Reilly Media. Kim has a keen interest in space flight and
aviation and has a private pilot’s license, which he would make more frequent use of if
the weather in England allowed it.
www.it-ebooks.info
Download from www.wowebook.com