logo资料库

JavaFX 2.0 電子書 - Pro JavaFX 2.pdf

第1页 / 共636页
第2页 / 共636页
第3页 / 共636页
第4页 / 共636页
第5页 / 共636页
第6页 / 共636页
第7页 / 共636页
第8页 / 共636页
资料共636页,剩余部分请下载后查看
Cover
Contents at a Glance
Contents
Foreword
About the Authors
About the Technical Reviewer
Acknowledgments
Getting a Jump Start in JavaFX
JavaFX Can’t Bring Rich-Client Java Back by Itself
A Brief History of JavaFX
Going to the Source: Oracle’s JavaFX Web Site
Accessing the JavaFX SDK API
Obtaining the JavaFX SDK
Other Available Tools
Developing Your First JavaFX Program: “Hello Earthrise”
Compiling and Running from the Command-Line
Understanding the Hello Earthrise Program
Building and Running the Program with NetBeans
Developing Your Second JavaFX Program: “More Cowbell!”
Building and Running the Audio Configuration Program
The Behavior of the Audio Configuration Program
Understanding the Audio Configuration Program
Creating an Instance of the Model, and the Magic of Binding
Colors and Gradients
The Model Class for the Audio Configuration Example
Defining Change Listeners in the Model class
Surveying JavaFX Features
Summary
Resources
Creating a User Interface in JavaFX
Introduction to Node-Centric UIs
Setting the Stage
Understanding the Stage Class
Using the Stage Class: The StageCoach Example
Understanding the StageCoach Program
Obtaining Program Arguments
Setting the Style of the Stage
Controlling Whether a Stage Is Resizable
Making a Stage Full Screen
Working with the Bounds of the Stage
Drawing Rounded Rectangles
Dragging the Stage on the Desktop When a Title Bar Isn’t Available
Using UI Layout Containers
Ascertaining Whether the Stage Is in Focus
Controlling the Z-Order of the Stage
Closing the Stage and Detecting When It Is closed
Making a Scene
Using the Scene Class: The OnTheScene Example
Understanding the OnTheScene Program
Setting the Cursor for the Scene
Painting the Scene’s Background
Populating the Scene with Nodes
Finding a Scene Node by ID
Accessing the Stage from the Scene
Inserting a Node into the Scene’s Content Sequence
CSS Styling the Nodes in a Scene
Handling Input Events
Surveying Mouse and Keyboard Events and Handlers
Understanding the KeyEvent Class
Understanding the MouseEvent Class
Animating Nodes in the Scene
Using a Timeline for Animation
The Metronome1 Example
Understanding the Metronome1 program
Understanding the Timeline Class
Inserting Key Frames into the Timeline
Controlling and Monitoring the Timeline
Using the Transition Classes for Animation
The MetronomeTransition Example
The Behavior of the MetronomeTransition Program
Understanding the MetronomeTransition Program
Using the TranslateTransition Class
Controlling and Monitoring the Transition
The MetronomePathTransition Example
The Behavior of the MetronomePathTransition Program
Understanding the MetronomePathTransition Program
Using the PathTransition Class
Drawing an Ellipse
The Zen of Node Collision Detection
Understanding the ZenPong Program
Using the KeyFrame Action Event Handler
Using the Node intersects() Method to Detect Collisions
Dragging a Node
Giving Keyboard Input Focus to a Node
Using the onKeyPressed Event Handler
Summary
Resources
Properties and Bindings
Forerunners of JavaFX 2.0 Binding
A Motivating Example
Understanding Key Interfaces and Concepts
Understanding the Observable Interface
Understanding the ObservableValue Interface
Understanding the WritableValue Interface
Understanding the ReadOnlyProperty Interface
Understanding the Property Interface
Understanding the Binding Interface
Type-Specific Specializations of Key Interfaces
A Common Theme for Type-Specific Interfaces
Commonly Used Classes
Creating Bindings
Understanding the Bindings Utility Class
Understanding the Fluent Interface API
Understanding the JavaFX Beans Convention
The JavaFX Beans Specification
Understanding the Eagerly Instantiated Properties Strategy
Understanding the Lazily Instantiated Properties Strategy
Using Selection Bindings
Summary
Resources
Building Dynamic UI Layouts in JavaFX
Introducing JavaFX Reversi
Board Layout and Basic Rules
Building a JavaFX Model for Reversi
Dynamic Layout Techniques
Centering Text Using Bind
Centering Revisited Using a StackPane
Aligning to Edges Using StackPanes and TilePanes
Using FlowPane and Boxes for Directional Alignment
Composing a Layout Using BorderPane
Creating Custom Regions
Building a Custom Square Region
Building a Resizable Reversi Piece
Laying Out the Tiles Using a GridPane
Aligning and Stretching with AnchorPane
When to Use Different Layouts
A New Perspective on Reversi: The JavaFX 3D Scene Graph
Bringing Reversi to Life
Highlighting Legal Moves
Highlighting the Active Cell
Taking Turns
Additional Game Enhancements
Summary
Resources
Using the JavaFX UI Controls
Trying Out the JavaFX UI Controls
Leveraging the JavaFX UI Controls
Setting the Stage for the StarterApp Program
Creating a Menu and Defining Menu Items
Creating a Toolbar
Defining Graphical Buttons
Defining Toggle Buttons
Using Toggle Groups
Inserting a Separator into a Toolbar
Creating a TabPane and Defining Tabs
Creating a TableView
Assigning Items to a Table
Defining TableView Columns
Detecting When a Row Is Selected
Creating an Accordion and Defining a TitledPane
Creating a TreeView
Defining a TreeItem
Detecting When a TreeItem Is Selected
Creating a ListView and Assigning Items to a ListView
Creating a SplitPane
Defining a ScrollPane
Using a CheckBox
Defining a RadioButton
Creating a Hyperlink
Defining a ChoiceBox
Using a MenuButton
Creating a ContextMenu
Creating a SplitMenuButton
Defining a TextField
Using a PasswordField
Creating a TextArea
Creating a Slider
Defining a ProgressIndicator
Defining a ScrollBar
Using a ProgressBar
Creating an HTMLEditor
Creating a Popup
Using a WebView
Summary
Resources
Collections and Concurrency
Understanding Observable Collections
Understanding ObservableList
Handling Change Events in ListChangeListener
Understanding ObservableMap
Using Factory and Utility Methods from FXCollections
Using the JavaFX Concurrency Framework
Identifying the Threads in a JavaFX Application
Fixing Unresponsive UIs
Understanding the javafx.concurrent Framework
Understanding the Worker Interface
Understanding the Task Abstract Class
Understanding the Service Abstract Class
Embedding JavaFX Scenes in Swing and SWT Applications
Summary
Resources
Creating Charts in JavaFX
Structure of the JavaFX Chart API
Using the JavaFX PieChart
The Simple Example
Some Modifications
Using the XYChart
Using the ScatterChart
A Simple Implementation
Improving the Simple Implementation
Using the LineChart
Using the BarChart
Using the AreaChart
Using the BubbleChart
Summary
Resources
Using the Media Classes
The Foundation
Supported Media Formats
Working with Audio Clips
Controlling the Playback Parameters of an AudioClip
Constructing the Scene
AudioClip Wrap-Up
Working with Media
Playing Audio
Error Handling
Displaying Metadata
Loading Media
Controlling Playback
Laying Out the Player Controls
Creating Playback Controls
Seeking
Controlling Volume
Repetition
Audio Equalization
MediaPlayer Wrap-Up
Playing Video
Controlling the Size of a MediaView
MediaView and Effects
Using Markers
One Player, Multiple Views
Converting AudioPlayer into a VideoPlayer
Summary
Accessing Web Services
Front-end and Back-end Platforms
Merging JavaFX and Java Enterprise Modules in the Same Environment
Using JavaFX to Call Remote (Web) Services
SOAP
REST
Setting Up the Application
Using the Twitter API
Using External Libraries
Summary
JavaFX Languages and Markup
A Quick Comparison of Alternative Languages
Vanishing Circles in Java
Vanishing Circles in Alternative JVM Languages
Making Your JavaFX Groovy
Introduction to GroovyFX
Properties in GroovyFX
GroovyFX Binding
GroovyFX API Enhancements
Animation
Tables
Layouts
Scala and JavaFX
Getting Started with ScalaFX
ScalaFX Proxies and Implicit Conversions
JavaFX Properties in Scala
ScalaFX Bind APIs
API Enhancements
Closures
Layout Constraints
Animation
Visage, the JavaFX Language
Advantages of Using Visage
Getting Started with Visage
Constructing UIs with FXML Markup
Learning FXML by Example
Controlling FXML Applications
Summary
Resources
The Visage Language in Depth
An Overview of Visage
Variables, Values, and Their Types
Variable Names
Variable Types
Primitive Types
Boolean Type
Boolean Literals and the Default Value
Boolean Operators
The Backing Class of the Boolean Type
Integer Type
Integer Literals and the Default Value
Arithmetic Operators
The Backing Class of the Integer Type
Character Type
Sources of Character Values and the Default Value
Arithmetic Operations
The Backing Class of the Character Type
Byte, Short, and Long Types
Sources of Byte and Short Values, Long Literals, and the Default Values
Arithmetic Operations
The Backing Classes of the Byte, Short, and Long Types
Float and Number Types
Number Literals and the Default Value
Arithmetic Operations
The Backing Class of the Number Type
Double Types
Double Literals and the Default Value
The Backing Class of the Double Type
String Type
String Literals and the Default Value
String Expressions
The Backing Class of the String Type
Duration Type
Duration Literals and the Default Value
Arithmetic Operations Involving Durations
The Backing Class of the Duration Type
Length Type
Length Literals and the Default Value
Core Types of Length Literals
Length Arithmetic and Conversions
The Backing Class of the Length Type
Angle Type
Angle Literals and the Default Value
Angle Arithmetic and Conversions
The Backing Class of the Angle Type
Color Type
Color Literals and the Default Value
Color Arithmetic
The Backing Class of the Color Type
Working with Sequences
Sequence Types
Constructing Sequences Using Explicit Sequence Expressions
Constructing Numeric Sequences Using Range Expressions
Manipulating Sequences
Accessing the Size of a Sequence
Accessing an Element in a Sequence
Accessing a Slice of a Sequence
Accessing a Subset of a Sequence Through a Predicate
Reversing a Sequence
Inserting an Element into a Sequence
Inserting Another Sequence into a Sequence
Deleting Elements from a Sequence
Sequence Manipulation Example
Comprehending Sequences
Using Utility Functions in visage.util.Sequences
Visage Expressions
Expressions and Their Types
Block Expression
Precedence and Groupings
Expression Separator
Variable and Constant Declarations
Assignment Operator
Compound Assignment Operators
Relational Operators
While Expression
Revisiting the for Expression
If Expression
Object Literals
Classes and Objects
The Object Literal Expression
Initializing Instance Variables
Default Instance Variables
Declaring Constants and Variables
Overriding Instance Functions and Instance Variables
Manipulating Objects
Manipulating Object States
Invoking Instance Functions
Handling Nulls in Visage
Creating Java Objects with the new Operator
Making of a Declarative Syntax
Working with Data Bindings
Bind Expression
What Does the Data Binding Remember?
Binding to if Expressions
Binding to for Expressions
Binding to a Block
Binding to Function Invocation Expressions
Binding to Object Literal Expressions
Bidirectional Bindings and Lazy Bindings
Working with Functions
Function Definitions
Return Types
Parameters and Their Types
Function Bodies and the Return Expression
Function Body Scope
Overloaded Functions
Implicit Type Conversions
Resolving Overloaded Functions
Function Types and Anonymous Functions
More Details on Function Type Specifiers
More Details on Anonymous Function Expressions
More Details on Closures
Bound Functions
Handling Exceptions
The Call Stack
Throwing Exceptions
Handling Exceptions
Working with Classes
Class Definitions
Instance Variables
Declaring Default Instance Variables
Instance Functions
The this Expression
init Blocks
Creating Class Hierarchies
Mix-in Classes
Extending Classes
Overriding Instance Variables
Overriding Instance Functions
The super Keyword
Using Abstract and Mix-in Classes
Conflict Resolution in Mix-in Inheritance
Casting and the instanceof and as Operators
Organizing Visage Code
Scripts
Modules
A Special Provision for Classes
Packages
Import Directives
Access Modifiers
Protected Modifiers
public-init and public-read Modifiers
Triggers
Accessing the Old and New Values in Trigger Blocks
Accessing Sequence Modification Information in Trigger Blocks
Debugging with Triggers
String Formatting and Internationalization
Using String Format Specifications
Internationalizing Visage Programs
Leveraging Java from Visage
Instantiating Java Classes
Accessing Java Object Fields
Calling Java Methods
Accessing Static Fields and Methods
Quoting Visage Keywords
Accessing Nested Classes
Accessing Java Enums
Extending Java Classes and Interfaces
Dealing with Java Arrays
Iterating Through Java Collections
Visage Reflection
Mirror-Based Reflection
Entering the Reflection World
Programming Through Reflection
Getting and Setting Values of Instance and Script Variables
Invoking Instance and Script Functions
Other Reflection Capabilities
Resources
Index
A
B
C
E
F
G
H
I
J
K
L
M
O
S
T
U
V
W, X, Y, Z
For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them.
Contents at a Glance Foreword .................................................................................................................. xv About the Authors .................................................................................................... xvi About the Technical Reviewer ............................................................................... xviii Acknowledgments ................................................................................................... xix ■ Chapter 1: Getting a Jump Start in JavaFX ............................................................. 1 ■ Chapter 2: Creating a User Interface in JavaFX ..................................................... 35 ■ Chapter 3: Properties and Bindings ....................................................................... 93 ■ Chapter 4: Building Dynamic UI Layouts in JavaFX ............................................. 137 ■ Chapter 5: Using the JavaFX UI Controls ............................................................. 183 ■ Chapter 6: Collections and Concurrency ............................................................. 231 ■ Chapter 7: Creating Charts in JavaFX .................................................................. 307 ■ Chapter 8: Using the Media Classes .................................................................... 335 ■ Chapter 9: Accessing Web Services .................................................................... 391 ■ Chapter 10: JavaFX Languages and Markup ....................................................... 431 ■ Appendix: The Visage Language in Depth ............................................................ 477 Index ....................................................................................................................... 609 iii
C H A P T E R 1 Getting a Jump Start in JavaFX Don’t ask what the world needs. Ask what makes you come alive, and go do it. Because what the world needs is people who have come alive. —Howard Thurman At the annual JavaOne conference in May 2007, Sun Microsystems announced a new product family named JavaFX. Its stated purpose includes enabling the development and deployment of content-rich applications on consumer devices such as cell phones, televisions, in-dash car systems, and browsers. Josh Marinacci, a software engineer at Sun, made the following statement very appropriately in a recent Java Posse interview: “JavaFX is sort of a code word for reinventing client Java and fixing the sins of the past.” Josh was referring to the fact that Java Swing and Java 2D have lots of capability, but are also very complex. JavaFX allows us to simply and elegantly express user interfaces (UIs) with a declarative programming style. It also leverages the full power of Java, because you can instantiate and use the millions of Java classes that exist today. Add features such as binding the UI to properties in a model and change listeners that reduce the need for setter methods, and you have a combination that will help restore Java to the client side of the RIA equation. In this chapter, we give you a jump start in developing JavaFX applications. After bringing you up to date on the brief history of JavaFX, we show you how to get the JavaFX software development kit (SDK). We also explore some great JavaFX resources and walk you through the process of compiling and running JavaFX applications. In the process you’ll learn a lot about the JavaFX API as we walk through application code together. First, however, we point out a related technology that is enabling the rise of rich-client Java. JavaFX Can’t Bring Rich-Client Java Back by Itself When Java was first introduced in 1995, the hope was that the Java Runtime Environment (JRE) would become the common client platform on which the UI portion of client–server applications could be deployed. Although the JRE became ubiquitous on the server side of the equation, factors such as the browser wars of the late 1990s delayed the prospect of achieving a consistent JRE on client machines. The result has been that web browser technologies such as HTML and JavaScript have stepped in to fill the gap, which we feel has proven suboptimal at best. The software development industry and the users we serve need to have the JRE on all client machines so that we can break free from browser technologies and enable graphically rich, fast-performing applications. Fortunately, the technology known as Java SE 6 Update 10 is solving that problem. 1
CHAPTER 1 ■ GETTING A JUMP START IN JAVAFX Note What has come to be known as Java SE 6 Update 10 has actually had several names. It started life as the Consumer JRE, and then Java SE 6 Update N. Then it became known as Java SE 6 Update 10. As of this writing, Java SE 7 has been released, but we just refer to this technology as Java SE 6 Update 10. Java SE 6 Update 10 consists of several technologies that improve the user experience related to installing the JRE, and to deploying and running rich-client Java (and JavaFX) programs: • • • • • Java Kernel Online Installer—The JRE is now divided into small bundles. If the user’s machine doesn’t have the JRE installed when a Java program is invoked, the online installer will ascertain which of the bundles are needed to run the program. Those bundles will be installed first and the program will begin executing as soon as this takes place. Java Auto-Updater: This provides a faster and more reliable process for updating the JRE by using a patch-in-place mechanism. Java Quick Starter: After a cold boot of the system, portions of the JRE are prefetched into memory. This enables a Java program to start more quickly. Pack200 Format: Pack200 is a highly compressed format that enables Java libraries and resources, for example, to download more quickly than traditional JAR files. Java Deployment Toolkit: This includes a simple JavaScript interface with which to deploy Java applets and applications. The JavaScript library is located at a well- known URL, and is engineered to make the right deployment decisions based on the detected JRE environment on the user’s machine. • Next Generation Java Plug-In: This Java plug-in is much more reliable and versatile than its predecessor. For example, you now have the ability to specify large heap sizes, and per-applet command-line arguments. Also, it has built-in Java Network Launching Protocol (JNLP) support as well as improved Java/JavaScript communications. • Hardware Acceleration Support: In a media-rich environment, it is crucial to take advantage of the graphics capabilities on the underlying hardware. For example, Java SE 6 Update 10 currently has a hardware accelerated graphics pipeline based on the Microsoft Direct3D API. This is a predecessor to the new Prism pipeline that JavaFX uses. The net result is that we are now at a point in software development history when two technologies (JavaFX and Java SE 6 Update 10) are working together to restore rich client Java. We feel that sanity is in the process of being restored to Internet software development, and we want you to join us in this RIA revolution. But first, a brief history lesson about JavaFX. A Brief History of JavaFX JavaFX started life as the brainchild of Chris Oliver when he worked for a company named SeeBeyond. They had the need for richer user interfaces, so Chris created a language that he dubbed F3 (Form 2 ■
CHAPTER 1 ■ GETTING A JUMP START IN JAVAFX Follows Function) for that purpose. In the article, “Mind-Bendingly Cool Innovation” (cited in the Resources section at the end of this chapter) Chris is quoted as follows. “When it comes to integrating people into business processes, you need graphical user interfaces for them to interact with, so there was a use case for graphics in the enterprise application space, and there was an interest at SeeBeyond in having richer user interfaces.” SeeBeyond was acquired by Sun, who subsequently changed the name of F3 to JavaFX, and announced it at JavaOne 2007. Chris joined Sun during the acquisition and continued to lead the development of JavaFX. The first version of JavaFX Script was an interpreted language, and was considered a prototype of the compiled JavaFX Script language that was to come later. Interpreted JavaFX Script was very robust, and there were two JavaFX books published in the latter part of 2007 based on that version. One was written in Japanese, and the other was written in English and published by Apress (JavaFX Script: Dynamic Java Scripting for Rich Internet/Client-Side Applications, Apress, 2007). While developers were experimenting with JavaFX and providing feedback for improvement, the JavaFX Script compiler team at Sun was busy creating a compiled version of the language. This included a new set of runtime API libraries. The JavaFX Script compiler project reached a tipping point in early December 2007, which was commemorated in a blog post entitled “Congratulations to the JavaFX Script Compiler Team—The Elephant Is Through the Door.” That phrase came from the JavaFX Script compiler project leader Tom Ball in a blog post, which contained the following excerpt. An elephant analogy came to me when I was recently grilled about exactly when the JavaFX Script compiler team will deliver our first milestone release. “I can’t give you an accurate date,” I said. “It’s like pushing an elephant through a door; until a critical mass makes it past the threshold you just don’t know when you’ll be finished. Once you pass that threshold, though, the rest happens quickly and in a manner that can be more accurately predicted.” A screenshot of the silly, compiled JavaFX application written by one of the authors, Jim Weaver, for that post is shown in Figure 1-1, demonstrating that the project had in fact reached the critical mass to which Tom Ball referred. Figure 1-1. Screenshot for the “Elephant Is Through the Door” program 3
CHAPTER 1 ■ GETTING A JUMP START IN JAVAFX Much progress continued to be made on JavaFX in 2008: • The NetBeans JavaFX plug-in became available for the compiled version in March 2008. • Many of the JavaFX runtime libraries (mostly focusing on the UI aspects of JavaFX) were rewritten by a team that included some very talented developers from the Java Swing team. • In July 2008, the JavaFX Preview SDK was released, and at JavaOne 2008 Sun announced that the JavaFX 1.0 SDK would be released in fall 2008. • On December 4, 2008, the JavaFX 1.0 SDK was released. This event increased the adoption rate of JavaFX by developers and IT managers because it represented a stable codebase. • • In April 2009, Oracle and Sun announced that Oracle would be acquiring Sun. The JavaFX 1.2 SDK was released at JavaOne 2009. In January 2010, Oracle completed its acquisition of Sun. JavaFX 1.3 SDK was released in April 2010, with JavaFX 1.3.1 being the last of the 1.3 releases. At JavaOne 2010, JavaFX 2.0 was announced. The JavaFX 2.0 roadmap was published by Oracle on the Web page noted in the Resources section below, and includes items such as the following. • Deprecate the JavaFX Script language in favor of using Java and the JavaFX 2.0 API. This brings JavaFX into the mainstream by making it available to any language (such as Java, Groovy, and JRuby) that runs on the JVM. • Make the compelling features of JavaFX Script, including binding to expressions, available in the JavaFX 2.0 API. • Offer an increasingly rich set of UI components, building on the components already available in JavaFX 1.3. • Provide a Web component for embedding HTML and JavaScript content into JavaFX applications. Enable JavaFX interoperability with Swing. • • Rewrite the media stack from the ground up. JavaFX 2.0 was released at JavaOne 2011, and has enjoyed a greatly increased adoption rate due to the innovative features articulated previously. Now that you’ve had the obligatory history lesson in JavaFX, let’s get one step closer to writing code by showing you where some examples, tools, and other resources are. Going to the Source: Oracle’s JavaFX Web Site Oracle’s JavaFX.com site is a great resource for seeing example JavaFX programs, downloading the JavaFX SDK and tools, taking tutorials on JavaFX, and linking to other resources. See Figure 1-2 for a screenshot of this web site. 4
CHAPTER 1 ■ GETTING A JUMP START IN JAVAFX Figure 1-2. Oracle’s official JavaFX web site In addition, blogs maintained by JavaFX engineers and developers are great resources for up-to-the- minute technical information on JavaFX. For example, Oracle JavaFX Engineers Richard Bair, Jasper Potts, and Jonathan Giles keep the developer community apprised of the latest JavaFX innovations at http://fxexperience.com. In addition, the Resources section at the end of this chapter contains the URLs of the blogs that the authors of this book use to engage the JavaFX developer community. Take a few minutes to explore these sites. Next we point out some more valuable resources that are helpful. Accessing the JavaFX SDK API A useful resource available from the JavaFX sites is the SDK API JavaDoc documentation, shown in Figure 1-3. 5
分享到:
收藏