JavaFX Rich Client Programming On The NetBeans Platform

Transcription

JAVAFXRICH CLIENTPROGRAMMING ON THENETBEANS PLATFORM

This page intentionally left blank

JAVAFXRICH CLIENTPROGRAMMINGON THENETBEANS PLATFORMGAIL ANDERSON PAUL ANDERSONSaddle River, NJ Boston Indianapolis San FranciscoNew York Toronto Montreal London Munich Paris MadridCapetown Sydney Tokyo Singapore Mexico City

Many of the designations used by manufacturers and sellers to distinguish their prod‐ucts are claimed as trademarks. Where those designations appear in this book, andthe publisher was aware of a trademark claim, the designations have been printedwith initial capital letters or in all capitals.The authors and publisher have taken care in the preparation of this book, but makeno expressed or implied warranty of any kind and assume no responsibility for errorsor omissions. No liability is assumed for incidental or consequential damages in con‐nection with or arising out of the use of the information or programs containedherein.For information about buying this title in bulk quantities, or for special salesopportunities (which may include electronic versions; custom cover designs; and con‐tent particular to your business, training goals, marketing focus, or brandinginterests), please contact our corporate sales department at corpsales@pearsoned.comor (800) 382‐3419.For government sales inquiries, please contact governmentsales@pearsoned.com.For questions about sales outside the U.S., please contactinternational@pearsoned.com.Visit us on the Web: informit.com/awLibrary of Congress Control Number: 2014947363Copyright 2015 Anderson Software Group, Inc.All rights reserved. Printed in the United States of America. This publication is pro‐tected by copyright, and permission must be obtained from the publisher prior to anyprohibited reproduction, storage in a retrieval system, or transmission in any form orby any means, electronic, mechanical, photocopying, recording, or likewise. To obtainpermission to use material from this work, please submit a written request to PearsonEducation, Inc., Permissions Department, One Lake Street, Upper Saddle River, NewJersey 07458, or you may fax your request to (201) 236‐3290.ISBN‐13: 978‐0‐321‐92771‐2ISBN‐10: 0‐321‐92771‐0Text printed in the United States on recycled paper at RR Donnelley in Crawfordsville, Indiana.First printing, September 2014

ContentsForewordxviiPrefacexixAbout the AuthorsxxiiiChapter 1A Tour of the NetBeans PlatformWhat You Will Learn1.11Background Basics 2JavaFX Integration1.212The NetBeans Platform: The Big Picture3Module System API 3Lookup API 5Window System API 5File System API 7Nodes and Explorer Views 7But Wait . . . There’s More 81.3FamilyTreeApp Reference ApplicationFamilyTreeApp and JavaFX 11JavaFX 3D Integration Possibilities1.41.51.61.715Documentation 17How to Get Java and the NetBeans Platform SoftwareExample Software Bundle 18Key Point Summary 18Chapter 2Background BasicsWhat You Will Learn2.110171920JavaBeans and PropertiesCreating a Java ApplicationBound Properties 292025v

viContentsCoarse-Grained Notification for JavaBean Objects2.2Lambda Expressions38Lambda Expressions with Functional InterfacesFunctional Data Structures 392.3Swing Basics 40Creating a GUI-Form Project 41Swing Form Designer 44Program Structure 47Single-Threaded Model 49Java Logging Facility 51Using Swing Components 54Event Handlers and Loose Coupling2.42.571Swing Background Tasks 73Introducing SwingWorker 73Monitoring SwingWorker Status2.759Improving the User Experience 63Concurrency and Thread Safety 68Thread-Safe Objects 68Adding Listeners and Thread SafetyConcurrency in Swing 722.6Key Point SummaryWhat’s Next?Chapter 3768081Introduction to JavaFXWhat You Will Learn 833.1What Is JavaFX? 84A Bit of History 84The Scene Graph Metaphor 85Single-Threaded Model 863.238Building JavaFX Programs 87Creating a JavaFX Application 88Java APIs 88Creating a JavaFX FXML ApplicationCSS Files 98Animation 100938333

Contents3.3JavaFX Properties103What Is a JavaFX Property? 103Using Listeners with Observable PropertiesRead-Only Properties 109Binding 1093.43.5Putting It All Together 120Key Point Summary 128What’s Next?Chapter 4129Working with JavaFXWhat You Will Learn4.1105131131Creating JavaFX Properties132JavaFX Properties with Lazy Evaluation 133Object Properties 134Immutable Properties 135Computed Properties 135Methods equals() and hashCode() 1384.2Using JavaFX Properties in a JavaFX ApplicationCreating a JavaFX FXML Application4.34.4139Observable Collections 148JavaFX Applications 153Program Structure 154Scene Builder and FXML 155JavaFX Controls 160JavaFX Controller Class 1654.5Concurrency and Thread Safety172Concurrency in JavaFX 173Observable Properties and Thread Safety4.6173JavaFX Background Tasks 176Worker and Task 176ProgressIndicator 1784.7Monitoring Background Tasks 182Using Method updateValue() 183Updating a Read-Only JavaFX Property187139vii

viiiContentsUpdating the JavaFX Scene Graph from a Background Task4.8Key Point SummaryChapter 5195A Taste of Modularity199What You Will Learn 1995.1Modular Architecture199Modules 200NetBeans Runtime Container5.25.3201Creating a NetBeans Platform Application 203Creating Modules 208Creating a NetBeans Module 209Creating Additional Modules 2115.45.5Configuring a Module with Public PackagesRegistering a Service Provider 214Global Lookup5.65.7218Configuring a Window for Selection219Porting Swing UI Code to a TopComponentLookup API 224Configuring the TopComponent 227223Configuring a Window with Form Editing 231Another Look at Lookup5.8239Module Life Cycle Annotations 242Using @OnStart 242Using @OnStop 2435.95.10What We Know So Far 244Key Point Summary 245What’s Next?Chapter 6247JavaFX Integration249What You Will Learn 2496.1211JavaFX and the NetBeans Platform 250Java 8 and JavaFX 8 Enhancements 251Create a NetBeans Platform Application 252191

ContentsCreate a NetBeans Module 253Add a Window to the Module 255Add JavaFX Content to the TopComponentThe Magic of JFXPanel 259SwingNode 2606.2Communication Strategies 261Accessing the JavaFX Controller Instance6.3256264Integrating with the NetBeans Platform 265Create a NetBeans Platform Application 267Create NetBeans Platform Modules 268Configure a Module with Public Packages 269Register a Service Provider 271Configure a Window with JavaFX for Selection 275Configure a Window with JavaFX for Form Editing 2836.4Key Point SummaryChapter 7Nodes and Explorer ViewsWhat You Will Learn7.17.2289291The NetBeans Model View Controller 292Nodes 293NodeListener and PropertyChangeListenerBuilding a Node Hierarchy 295Displaying the Node Hierarchy 303A Multi-Level Node Hierarchy 304Using BeanNode 310Creating Your Own Property Sheet 314Using FilterNode 3177.3295Explorer Views 323Quick Search 323BeanTreeView 324OutlineView 324Master-Detail View 327PropertySheetView 3317.4Creating a Selection History Feature 332Add Features to Your Application335291ix

xContents7.5Key Point SummaryChapter 8338NetBeans Platform Window SystemWhat You Will Learn 3428.1Window Framework Overview342Window Layout 342Window Modes 345TopComponents 346Window Operations 346Limiting the Window System’s BehaviorWindow Switching 350Window Tab Customization 350Window Manager 3508.2TopComponent Basics 352TopComponent Java Code 356Window Header Animated Notifications8.3TopComponent PersistenceWindows2Local Folder8.48.58.78.8361TopComponent Client Properties 363Creating Non-Singleton TopComponents 364367Window System Life Cycle Management 369Using the Window ManagerUsing @OnShowing 374373TopComponent ModesWindow Groups 381376Window Group Example8.9360363Opening Windows from User Code8.6349382Window Layout 387Creating TopComponents 395A View-Only Window Layout 3958.10Window Layout Roles401RoleExample Application and Role-Based TopComponentsCredential Checking and Role Assignments 405LoginTopComponent 408404341

Contents8.11Key Point SummaryChapter 9Action Framework 413What You Will Learn9.1410Type of Actions413414Always-Enabled Actions9.2414Actions and Lookup 421Callback Actions 422Context-Aware Actions9.3428Editing the Node Hierarchy 444Group Window Node Actions 445Reorder and Index.Support 451Implementing Drag and Drop 453Implementing Cut, Copy, Paste, Delete9.4Inter-Window Drag and Drop 458Trash Window Node Actions 458Implementing Drag and Drop Delete9.5Key Point SummaryChapter 10463468Building a CRUD ApplicationWhat You Will Learn10.1456471471Create-Read-Update-Delete Application 472Defining Capabilities 474Implementing Read 475Implementing Delete 480Implementing Create 482Implementing Update 48810.2Using CRUD with a Database501Create Wrapped Libraries 502JavaDB Server and Database 505Implement FamilyTreeManager 50610.3Concurrency in the FamilyTreeApp Application 516Concurrency with Read 517Concurrency with Delete and Create520xi

xiiContentsConcurrency with Update10.4Key Point SummaryChapter 11Dialogs522523525What You Will Learn 52511.111.2Dialog Overview 526Standard Dialogs 527NotifyDescriptor.Message 527NotifyDescriptor.Confirmation 529NotifyDescriptor.InputLine 53111.311.4Customizing Standard Dialogs 531Custom Dialogs 533Error Handling11.511.611.7535Custom Login Dialog 539Putting It All Together 544RoleExample Application545Key Point Summary548Chapter 12Wizards551What You Will Learn 55112.112.2Wizard Overview 552The Wizard Wizard 554A Bare-Bones Wizard 555Registering a Wizard’s Action12.312.4558Wizard Input 561Wizard Validation 565Coordinating Input with Other Panel WizardsVisual Panel Updates 57412.5Simple Validation API577Prepare to Use the Validation Library 578Using the Simple Validation API Library 580Using a Custom Validator 58312.6Finishing Early Option587572

Contents12.712.8Asynchronous Validation 592Dynamic Sequence Wizards 598Building the Dynamic Step Wizard 600The PizzaWizardIterator 605IdentifyCustomer Panel 609BuildPizza Panel 610Create the OrderPizzaAction 61212.9 Wizard Instantiating Iterators 61412.10 Key Point Summary 620Chapter 13File SystemWhat You Will Learn13.113.2623623File System API 624The File System API Overview624Exploring the FileSystem API 625The Output Window 628Create a Folder 630Get or Create a File in a Folder 631Write to and Read from Files 632Rename and Delete Files 634File System API Useful Methods 63513.3Monitoring File Changes636FileObject Attributes 637Favorites Window 637Implementing the FileChangeListener13.4646Including a File with Your Application 649Install a File in a Module 650Using the InstalledFileLocator Service 653Installing an NBM in NetBeans IDE 65413.5The Layer File and System FileSystem 654Layer Files and Configuration 655Exploring the System FileSystem 661Using the Layer File for Inter-Module Communication13.6Key Point Summary668665xiii

xivContentsChapter 14Data System671What You Will Learn 67114.1Data System API Overview 672FileObject, DataObject, and Node 673FileObject MIME Type and Lookup 674DataObject Factory and DataObject Lookup 675Accessing FileObjects from DataObjects 676DataObjects and Nodes 676Using DataNode and Lookup 67714.2Creating a New File Type 678Create a New File Type 681Create and Edit a New FTR File 688Provide Child Nodes Based on Content14.3Working with MultiView Windows 697Using the Visual LibraryUsing JavaFX 70814.4694699Creating an XML-Based File Type721Create a New XML File Type 725Add the XML Text Editor 731Add JavaFX Content 73514.5Key Point SummaryChapter 15740JavaFX Charts743What You Will Learn 74315.1JavaFX Charts and the NetBeans Platform 744Application Overview 746Working with AbstractTableModelWorking with Swing JTable 752Integrating JavaFX Charts 75515.2Introducing JavaFX Charts 759JavaFX Chart Overview15.3748759Data Visualization with JavaFX Charts 764Line Chart 764Scatter Chart 767

ContentsxvBar Chart 768Area Chart 770Stacked Area Chart 771Stacked Bar Chart 772Bubble Chart 773Pie Chart 77615.4Adding Behaviors to JavaFX Charts 781Accessing JavaFX Chart Nodes 782Adding PieChart Features 78415.515.6Saving Charts 789Key Point SummaryChapter 16Using Web ServicesWhat You Will Learn16.116.2795799799RESTful Web Services and the NetBeans Platform 800Creating RESTful Web Services 802Create Database 802Create RESTful Web Service Application 803RESTful Services from Database 804Entity Classes and JavaFX Properties 807Test the Web Services 80916.316.4A Java Application Web Service Client 810RESTful Web Services in a NetBeans Platform Application 817Generate RESTful Web Service Clients 817Application Overview 821Using JavaFX Services 821Implementing a RESTful Client Service ProviderJavaFX TableView 831JavaFX Chart Module 84016.5Key Point SummaryChapter 17827845Branding, Distribution, andInternationalization 847What You Will Learn847

xviContents17.1What Is Branding?848Using the Branding Menu 848Customizing the Application Title 852Customizing the Splash Screen 85517.2Application Updates 857Enable Updates of Your Application 857Create an Update Center 858Dynamically Uninstall a Module (Plugin) 860Adding Modules to an Application 861Install a Plugin 86317.3Application Distribution 864Create an Installer 865Installing the Application 867Customizing the Installer Images17.4867Application Internationalization 868Internationalization and Java 869Internationalization and the NetBeans Platform 870Number Formatting 872Editing Properties Files 873Internationalization and JavaFX 873Testing Target Locales 876NetBeans Platform Application Internationalization 876Customizing Resource Bundles 88117.5IndexKey Point Summary885883

Foreword“The NetBeans Platform abides,” is what the Dude in the Big Lebowski might havesaid, had he known about the NetBeans Platform at all, which he probably did, some‐how. Over the years, an incredibly wide range of applications have been built on topof the application framework that is the NetBeans Platform, from air defense systemsat NATO to medical applications at Stanford, from military software at NorthropGrumman to software development tools at Oracle. . . and hundreds, probably thou‐sands, of other applications in between.Even whilst the uninitiated queried the relevance of the NetBeans Platform—at firstchallenging NetBeans Platform users with “what about the browser?” and then a fewyears later with “what about mobile devices?”—those using the NetBeans Platformhave always known its applicability to the niche in which it fits so well. There willalways be a need to put together modular applications that run on the desktop, andcross‐platform portability will always be a predominant concern, making Java in com‐bination with the NetBeans Platform a uniquely well‐suited environment for seriousapplication developers.There certainly is something deeply intellectual about working with the NetBeansPlatform. Once you’re out of the woods of the initial learning experience, you will dis‐cover that you’re not only figuring out how to construct a puzzle out of a disparate setof pieces, but that the pieces themselves are objects that you’re constructing. There’s ameta‐level of enjoyment that is a strangely distinct feature of progressing in yourunderstanding of the NetBeans Platform and all it provides.Moreover, as this book shows throughout, what Swing and JavaFX have in common isthat they’re UI toolkits, not application frameworks. Neither of these toolkits providesany infrastructure to connect the pieces together. The NetBeans Platform is an appli‐cation framework for both toolkits, either separately or together. In fact, as you willquickly learn in this book, the NetBeans Platform is a meeting point that unites thestability and depth of experience that Swing developers bring to the table togetherwith the innovation and the rich content that the JavaFX world provides.I wish you a lot of fun as you acquire new knowledge with the NetBeans Platform,while learning how to create meaningful applications in Java.Geertjan WielengaNetBeans Product Managerxvii

This page intentionally left blank

PrefaceThe NetBeans Platform provides a rich client framework to build desktop applica‐tions in Java and JavaFX. Its design has a certain symmetry and elegance. As you useits many APIs, each new feature learned will become familiar. You’ll learn that thisfamiliarity, coupled with code and design reuse, is a good trait.Simply stated, the NetBeans Platform will save you years in building and maintainingapplication framework code. Even the simplest NetBeans Platform application hasamazing features. And the platform’s best feature is that as users change and technol‐ogy and requirements evolve, your application can evolve, too.Our ApproachThis book takes a holistic approach to presenting the NetBeans Platform. We beginwith the basic Java architectural tenets of event notification, JavaBeans property sup‐port, and UI responsiveness with background tasks. As we build upon these Javabasics, we present the NetBeans Platform APIs and features in the context of smallsample applications. For example, you will learn how the Nodes API, Action frame‐work, Lookup API, and modular architecture all contribute to the overall design of aCRUD‐based database application. Our examples are relatively small and familiar, soyou can spend more time learning the NetBeans Platform APIs and not our applica‐tion business logic.We wanted to write a book that pulls together many of the excellent NetBeans Plat‐form tutorials and documentation so that you don’t have to search for examples. Tothat end, we provide you with a lot of sample code including screen shots and step‐by‐step instructions to help you on your journey.And finally, this book is not just about the NetBeans Platform. With this text, we wantto encourage Swing programmers out there to take the plunge with JavaFX. If youwant to leverage the ease and beauty of JavaFX, the NetBeans Platform can help youtransition from a Swing UI to a JavaFX UI as you develop applications. In fact, themodular architecture of the NetBeans Platform is a great vehicle for easing intoJavaFX. Pinpoint your requirements that fit well with JavaFX and start there. Do yourvisualization requirements include charts or perhaps 3D? Maybe you’d simply like tohave stunning effects, such as linear gradients, drop shadows, or animations. Pick andchoose all you want, but know that you’ll still have the underpinnings of a modular,well‐designed NetBeans Platform application.xix

xxPrefaceAbout the ExamplesYou can download the source for the reference application (described briefly in“FamilyTreeApp Reference Application” on page 10) at https://java.net/projects/nbfamilytreeapp. You can download the remaining examples and projects describedin this book at tional ConventionsWe’ve applied a rather light hand with font conventions in an attempt to keep thepage uncluttered. Here are the conventions we follow.ElementFont ExampleJava/JavaFX classChildFactory, AbstractNode, Shape, CirclecodeRectangle rectangle new Rectangle(200, 100, Color.BLUE);rectangle.setEffect(new DropShadow());URLhttp://netbeans.orgfile namePerson.java, PersonEditor.fxmlkey combinationsCtrl SpaceNetBeans menu selectionsNew Windowcode within textThe animation affects the opacity property . . .code highlightingRectangle rectangle new Rectangle(200, 100, tArcHeight(30);rectangle.setEffect(new DropShadow());(to show modified or relevantportions)AcknowledgmentsFirst, we’d like to thank Geertjan Wielenga, without whose involvement, this bookwould not have been written. Geertjan provided both technical and philosophicalsupport and introduced us to the vast NetBeans Community.We’d also like to thank our readers. John Kimball provided much valuable feedbackthat especially shaped our early chapters. Both Mike Kelly and Stephen Voynar partic‐ipated in reading early versions of the chapters.Greg Doench, our editor at Pearson Technology Group, is a good friend and was avaluable part of this project. In fact, Greg has guided us through many book projects.Thank you as well to Elizabeth Ryan at Addison‐Wesley, who oversaw the book’s pro‐duction. Her attention to detail and keen eye kept the project on track with a fast‐

Prefacexxipaced production schedule. Our copy editor, Geneil Breeze, performed an amazingfeat in making our manuscript as consistent as possible.The NetBeans Platform has always had a strong, active community of software devel‐opers and technical writers. We’d especially like to thank the many members of theNetBeans Community who influenced and helped us in our NetBeans Platform jour‐ney, mostly without realizing it. Certain names appear over and over, contributingtechnical solutions to a myriad of questions asked by the community at large. We’dlike to thank and recognize Jaroslav Tulach, Geertjan Wielenga, Toni Epple, SvenReimers, Tim Boudreau, Tom Wheeler, Jesse Glick, Timon Veenstra, Sean Phillips, andmany others who have contributed to the NetBeans Platform body of knowledge.We’d like to give a shout out to Sharat Chander, who has given us opportunities tomeet and mingle with Java experts at home and internationally.In the JavaFX world, we’d like to thank those who are constantly sharing their knowl‐edge to further the acceptance of JavaFX. Stephen Chin, Jonathan Giles, Richard Bair,Brian Goetz, Jim Weaver, Gerrit Grunwald, and Carl Dea have all contributed to ourunderstanding of the finer points of JavaFX. And finally, we’d like to thank AdamBien, who has been a strong advocate and an early adopter of JavaFX for real‐worldapplications.Gail and Paul AndersonAnderson Software Group, Inc.www.asgteach.com

This page intentionally left blank

About the AuthorsGail Anderson and Paul Anderson are well‐known authors, having published bookson a wide range of Java technologies, including Enterprise JavaBean Components,Java Studio Creator Field Guide, and Essential JavaFX. In addition, Paul is the authorof JavaFX Programming LiveLessons and Java Reflection LiveLessons training videos. Pauland Gail are frequent speakers at JavaOne and cofounders of the Anderson SoftwareGroup, Inc., a leading provider of software training courses in Java and JavaFX.xxiii

This page intentionally left blank

This page intentionally left blank

3Introduction to JavaFXSwing has been around for a long time and some very powerful applications andframeworks are written with this library. One of those powerful applications is theNetBeans IDE, and one of those powerful frameworks is the NetBeans Platform. Justbecause these applications and frameworks are based on Swing, however, doesn’tmean you can’t or shouldn’t use JavaFX. Indeed, we hope that the material in thisbook will help you incorporate JavaFX into your NetBeans Platform applications, andby doing so, create rich client applications that both perform well and are beautiful.We begin with a nice, gentle introduction to JavaFX. But rest assured, we ramp up thematerial quickly in this chapter. Obviously, we can’t cover everything you need toknow about JavaFX here, but like the previous chapter’s presentation of Swing, wewant to give you enough so that you’ll be comfortable reading and using JavaFX codein desktop applications.In this chapter, you’ll learn the basics of JavaFX, its structure, and the philosophy ofhow JavaFX constructs a GUI. You’ll learn about different coding styles and discoverthe styles that best suit you and your development team. In the next chapter, we’llshow you how JavaFX fits into the world of desktop application development. We’llalso lay the groundwork for using JavaFX with the NetBeans Platform.What You Will Learn Understand JavaFX basics. Build JavaFX programs and use JavaFX APIs.83

84Chapter 3Introduction to JavaFX Build a scene graph with shapes, controls, and layout. Use FXML and controller classes. Incorporate CSS files into your JavaFX designs. Apply JavaFX animation and event handling. Understand JavaFX properties, observables, InvalidationListeners, and Change‐Listeners. Understand and apply JavaFX binding.3.1 What Is JavaFX?If the NetBeans Platform is written with Swing for its GUI and I already know Swing,why should I learn and use JavaFX? This is a good question. Here are several reasonswhy. JavaFX provides a rich graphical user interface. While you can certainly providerich content with Swing, JavaFX has the structure and APIs specifically for anima‐tion, 2D and 3D geometry, charts, special effects, color gradients, graphical con‐trols, and easy manipulation of media, including audio, video, and images. Thebottom line: you can create rich content a whole lot easier using JavaFX than withSwing and Java2D. JavaFX graphics rendering takes advantage of hardware‐accelerated capabilities.This makes rendering graphics and animation perform well. You can embed JavaFX content within Swing panels with JFXPanel. The magic ofthis specialized Swing component lets you create sophisticated NetBeans Platformapplications and include JavaFX rich content in your application windows. Fur‐thermore, you can start using JavaFX without throwing away existing Swing appli‐cations.A Bit of HistoryJavaFX began as a declarative scripting language (JavaFX Script) that was built on topof Java. While developers enjoyed the ease of a declarative script, it was difficult tointegrate JavaFX Script with existing Swing applications. Furthermore, JavaFX Scriptrequired learning a new language.JavaFX 2.0 was released in 2011 and is based on Java APIs. With Java 7, JavaFX isincluded in the standard release, and beginning with Java 8, which includes 3D capa‐bilities with JavaFX 8, all JavaFX libraries (JAR files) are included in the standard

3.1 What Is JavaFX?85classpath. This means that JavaFX is now part of the Java standard when you down‐load the Java Development Kit (JDK).While you can certainly use JavaFX APIs in the traditional Java coding style, JavaFXalso provides FXML, a declarative XML markup language that describes the graphicalcomponents in your application. Scene Builder is a stand‐alone application that gener‐ates FXML markup. With Scene Builder, you drag‐and‐drop controls and shapes todesign the UI in a visual editor. These coding options make it easier to construct com‐plicated UIs and work with user experience designers. You can also style your JavaFXapplication with CSS, a standard that is used and known by many designers. We’llintroduce FXML in this chapter and further explore FXML and Scene Builder in thenext chapter.The Scene Graph MetaphorJavaFX programs with a graphical user interface define a stage and a scene within thatstage. The stage represents the top‐level container for all JavaFX objects; that is, thecontent area for the application’s window frame. The central metaphor in JavaFX forspecifying graphics and user interface controls is a scene graph. A scene defines a hier‐archical node structure that contains all of the scene’s elements. Nodes are graphicalobjects, such as geometric shapes (Circle, Rectangle, Text), UI controls (Button, Tree‐View, TextField, ImageView), layout panes (StackPane, AnchorPane), and 3D objects.Nodes can be containers (parent nodes) that in turn hold more nodes, letting yougroup nodes together. The scene graph is a strict hierarchical structure: you cannotadd the same node instance to the graph more than once. Figure 3.1 shows the hierar‐chical structure of a JavaFX scene graph.Parent nodes are nodes that contain other nodes, called children. A child node with nochildren nodes is a leaf node. With parent nodes, you can include Panes (layout con‐tainers) and Controls (buttons, table views, tree views, text fields, and so forth). Youadd a node to a parent nt.getChildren().addAll(childNode1, childNode2);The power of the JavaFX scene graph is that, not only do you define the visual aspectof your application in a hierarchical structure, but you can manipulate the scene bymodifying node properties. And, if you manipulate a node property over time, youachieve animation. For example, moving a node means changing that node’s translateX and translateY properties over time (and translateZ if you’re working in 3D). Or,fading a node means changing that node’s opacity property over time. JavaFX proper‐ties are similar to the JavaBean properties we’ve already presented, but JavaFX prop‐

86Chapter 3Introduction to JavaFXStageStage: Top-level window frameCreated by JavaFX PlatformHas a sceneSceneScene: Contains a scene graphHas a root nodeRoot Node: Top node in sceneTypically a Parent nodeRoot/ParentNodeParent NodeLeaf Node.Parent NodeLeaf NodeLeaf NodeParent Node: Panes and ControlsContains other nodes (children).Leaf NodeLeaf Node: ShapesDoes not contain other nodesFigure 3.1 The JavaFX stage and sceneerties are much more powerful. Applying these transformations to a node generallypropagates to any of the node’s children as well.Single-Threaded ModelLike Swing, JavaFX uses a single‐threaded model. The JavaFX scene graph must bemanipulated in the JavaFX Application Thread, a separate thread from Swing’s EventDispatch Thread.1 Like Swing, working with a single‐threaded UI is mostly transpar‐ent: events are sent and received on the JavaFX Application Thread. And like Swing,threading issues arise when you create tasks to execute on a background thread. Thesolutions to these common programming scenarios are similar.How do JavaFX and Swing code co‐exist? Will you be writing intertwined graphicalspaghetti code? No, not at all. In this chapter you’ll learn about JavaFX without anySwing. Then when you learn how to integrate JavaFX into a NetBeans Platform appli‐cation window, you’ll see how to keep the JavaFX code separate, cohesive, and highlymodular. Both the NetBeans Platform architecture and JavaFX program structuremake it easy to add and maintain JavaFX rich content.1. There is experimental support in JDK 8 for making the EDT and JavaFX Application Thread(FXT)

Java Logging Facility 51 Using Swing Components 54 Event Handlers and Loose Coupling 59 2.4 Improving the User Experience 63 2.5 Concurrency and Thread Safety 68 Thread-Safe Objects 68 Adding Listeners and Thread Safety 71 Concurrency in Swing 72 2.6 Swing Background Tasks 73 Introducing SwingWorker 73 Monitoring SwingWorker Status 76 2.7 Key .