Mastering JavaFX 10 - Sergey Grinev - E-Book

Mastering JavaFX 10 E-Book

Sergey Grinev

0,0
34,79 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

JavaFX 10 is used to create media-rich client applications. This book takes you on a journey to use JavaFX 10 to build applications that display information in a high-performance, modern user interface featuring audio, video, graphics, and animation.
Mastering JavaFX 10 begins by introducing you to the JavaFX API. You will understand the steps involved in setting up your development environment and build the necessary dependencies. This is followed by exploring how to work with the assets, modules, and APIs of JavaFX. This book is filled with practical examples to guide you through the major features of JavaFX 10. In addition to this, you will acquire a practical understanding of JavaFX custom animations, merging different application layers smoothly, and creating a user-friendly GUI with ease.
By the end of the book, you will be able to create a complete, feature-rich Java graphical application using JavaFX.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 191

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering JavaFX 10
Build advanced and visually stunning Java applications
Sergey Grinev
BIRMINGHAM - MUMBAI

Mastering JavaFX 10

Copyright © 2018 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Commissioning Editor: Amarabha BanerjeeAcquisition Editor:Denim PintoContent Development Editor: Gauri PradhanTechnical Editor:Rutuja VazeCopy Editor:Safis EditingProject Coordinator:Sheejal ShahProofreader: Safis EditingIndexer:Tejal Daruwale SoniGraphics:Jason MonteiroProduction Coordinator:Shantanu Zagade

First published: May 2018

Production reference: 1290518

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78829-382-2

www.packtpub.com

To my mom, Raisa, and my wife, Irina, without whom this book would have never happened.
mapt.io

Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.

Why subscribe?

Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals

Improve your learning with Skill Plans built especially for you

Get a free eBook or video every month

Mapt is fully searchable

Copy and paste, print, and bookmark content

PacktPub.com

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.

Contributors

About the author

Sergey Grinev is an experienced software engineer focused on building reliable, quality processes for Java platforms. He started working in this area during his employment with Oracle, where he was responsible for JavaFX testing. For the last few years, Sergey has worked for Azul Systems, assuring the quality of their custom JVMs.

Sergey enjoys sharing his experience: he regularly presents Java conferences, gives lessons, and solves questions on Stack Overflow.

Writing a book is way harder than I thought, and I'm deeply grateful to the people who helped me. Thanks to my mother, Raisa, who made me study English from the age of 5. Thanks to my beloved family, Irina and Alexander, for always inspiring me and coping with a half-absent father. Thanks to my English teacher and friend, April, for the support and inspiration. Also, great thanks to my editor, Gauri, and the whole Packt team.

About the reviewer

Naman Nigam is a philomath currently working as a software developer with Flipkart. He is heavily involved in gamification and personalization platforms to develop services and features that are responsible for customer engagement at Flipkart. He keeps up to date with the technological upgrades available and their usages, while helping with code reviews, ensuring a consistent performance alongside.

The Flipkart tech team has been extremely helpful during the review process by providing environments where Naman was able to experiment with some of the latest Java releases.

I would like to thank my wife, Neha, who stood by me heedfully whenever I'd take out some time reviewing the book, and my friends who persistently encouraged me to be a part of it.

Packt is searching for authors like you

If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.

Table of Contents

Title Page

Copyright and Credits

Mastering JavaFX 10

Dedication

www.PacktPub.com

Why subscribe?

PacktPub.com

Contributors

About the author

About the reviewer

Packt is searching for authors like you

Preface

Who this book is for

What this book covers

To get the most out of this book

Download the example code files

Download the color images

Conventions used

Get in touch

Reviews

Stages, Scenes, and Layout

Application and JavaFX subsystems

Components of the JavaFX toolkit

Glass toolkit

Prism and Quantum Toolkit

Media

WebView/WebEngine

Working with JavaFX Application Thread

Application class

Using the Application.launch() method

Managing command-line parameters

Closing the JavaFX application

Stage – a JavaFX term for the window

Working with Stage modality options

Using Stage styles

Setting fullscreen and other window options

Scene and SceneGraph

Organizing the Scene content with Layout Managers

Free layout

The most basic layout manager – Group

Region and Pane layout managers

Behavioral layout

Positional layout

TilePane and FlowPane

BorderPane layout manager

AnchorPane layout manager

GridPane layout manager

Clock demo

Summary

Building Blocks – Shapes, Text, and Controls

Shapes and their properties

JavaFX shapes overview

Closed shapes

Lines

Curves

Paths

Adding Text to the JavaFX scene

Controlling Shape's color

Paint

ImagePattern

Gradients

Customizing lines with Stroke API

Basic Stroke

Dashed lines

Connecting line designs using Line Join

Working with the Shape operations

Transformations

Coordinates and bounds

Working with Bounds Demo

Using the ScenicView tool to study JavaFX scenegraph

Basic Controls

Button and Event Handlers

Size of the Controls

Clock demo

Summary

Connecting Pieces – Binding

Working with the Property API

Using the Observable API

Introducing the Binding API

Rules of binding

Read-only properties

Binding is a one-to-many relation

Binding blocks setters

Bidirectional binding

Using binding for visual help

The role of listeners

Using binding operations

String operations

Arithmetic operations

Boolean operations

Working with bidirectional binding and converters

Creating custom bindings

Implementing base binding classes

Bindings helper function

Understanding binding collections

Summary

FXML

Introduction to FXML

Basics of FXML

Benefits of FXML

Limitations of FXML

Working with FXML loaders

Working with resources

Using the FXMLLoader API

Working with the fx:root attribute and custom components

Working with Controllers

Enhancing Controllers

Using a preconstructed Controller

Working with data

Syntax details of FXML

Reviewing the basics of FXML

Importing packages

Including other FXML files

Using FXML defines

Default properties

Referring to resources from FXML

Adding business logic to FXML

Using static methods in FXML

SceneBuilder

Working with a WYSIWYG editor

Features

Specifying CSS files through the Preview menu

Localization in Preview

Summary

Animation

What is an animation?

Animation example

Understanding KeyFrame and KeyValue

Adding handlers and timers

Working with the Timeline API

Adding cue points

Using the Interpolator API

Predefined interpolators

Using transitions – the predefined animations

Using movement and resize transitions

Using TranslateTransition

Using PathTransition

Using RotateTransition

Using ScaleTransition

Working with color transitions

Combining transitions

Building an animated application

Summary

Styling Applications with CSS

Introduction to CSS

FirstStyles demonstration

Matching JavaFX nodes using selectors

Understanding naming convention for style classes and properties

Using type selectors

Styling specific objects using ID selectors

Loading CSS files from the JavaFX code

Applying styles to JavaFX nodes

Having several CSS files in one JavaFX application

Using the setStyle() method

Calling a corresponding API method

Referring to CSS styles from FXML

Using global JavaFX style sheets

Understanding cascading – the priority scheme for different styling methods

Working with advanced CSS syntax

Using pseudo-classes

Working with descendant selectors

Working with imports, fonts, and URLs

Working with constants and the inherit keyword

Why use CSS?

Using the CSS API

Introducing ClockControl

Adding a new style class

Using the new CSS property

Summary

Building a Dynamic UI

Tuning min and max size properties

Controlling node location with AnchorPane

Planning node size behavior with grow priorities

Fluid layouts

Enhancing applications with scrolling

Summary

Effects

Applying basic effects

Adding shadow effects

Using DropShadow

Using InnerShadow

Understanding the base Shadow effect

Adding reflections

Combining effects

Distorting using blur effects

Adding color effects

Using ColorAdjust

Using ColorInput

Using SepiaTone

Bloom and Glow

Applying lighting effects

Understanding the types of light

Using Distant light

Using Spot light

Using Point light

Using BumpInput

Transformation effects

Setting up PerspectiveTransform

Distorting an image with DisplacementMap

Using blend effects

Cutting out with the SRC_ATOP blend mode

Calculating the difference between images

Lightening and darkening

Other blend modes

Summary

Media and WebView

Working with web content

Presenting web content with WebView

Context menu

Accessibility features

Web engine

Handling page loading progress with LoadWorker

Loading content and user interface callbacks

Using Document Object Model

Running JavaScript on a page

Calling JavaFX code from JavaScript

Incorporating media into a JavaFX application

Adding audio clips

Working with the MediaPlayer and Media classes

Adding video through MediaView

Summary

Advanced Controls and Charts

Advanced controls

ListView

Managing ListView items

Using Selection and Focus API

Editable lists

Creating the TextFieldListCell

Editing through a ChoiceBox/ComboBox

Using CheckBox

Creating custom cells

Using TableView

TableModel

Creating and combining columns to form tables

Sorting

Observable Model

Making a table editable

Working with JavaFX charts

Creating a Pie chart

Creating a Line chart

Review of other XY charts

Custom controls

Skins

ClockControl demo

Java 9 and 10 API for skins

Summary

Packaging with Java9 Jigsaw

Handmaking JAR files

Running the demo project

Basic commands of the javapackager tool

Creating self-contained applications

Preparing OS-native installers with javapackager

Working with Jigsaw modules

Making our own module

Summary

3D at a Glance

Introduction to the JavaFX 3D API

Basic 3D elements

Adding Camera to the Scene

Lighting the Scene

Using Materials

Using Bump Map

Working with the Diffuse and Self-Illumination maps

Summary

What's Next?

Other materials

Official documentation of JavaFX

Stackoverflow.com

Working with JavaFX source code

Beyond the official API

Frameworks and libraries

Blogs

Future of JavaFX

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

JavaFX is a set of libraries added to Java in order to provide capabilities to build a modern UI. It was added to Java a few releases ago, as old libraries—Swing and AWT—proved to be outdated and too burdened with backward compatibility issues.

JavaFX was designed and developed from scratch to provide Java developers with the capabilities to build modern, rich UI applications with a large set of shapes, controls, and charts. It was designed with performance in mind, is capable of using graphics cards, and is based on the new graphical engine.

In this book, we will study many aspects of JavaFX and go through a large set of examples based on these topics.

Who this book is for

Developers who already use Java and want to add JavaFX to their skill set, students who study Java or computer science and want to use JavaFX to improve their projects, programmers familiar with JavaFX who want to enrich their experience and learn about the new features of the JavaFX 9 and 10 releases.

What this book covers

Chapter 1, Stages, Scenes, and Layout, starts from the essential basis of the JavaFX application—Stage, Scene, JavaFX Event Thread, and the layout graph concept.

Chapter 2, Building Blocks – Shapes, Text, and Controls, fills the window we created in the previous chapter with various building blocks provided by the JavaFX API.

Chapter 3, Connecting Pieces – Binding, explains that binding is a new method to greatly simplify communication between components.

Chapter 4, FXML, introduces FXML is a powerful tool for building a complex JavaFX UI and separating business logic from UI design. We will design an FXML application and try SceneBuilder—an FXML-based UI designer tool.

Chapter 5, Animation, demonstrates how to use the JavaFX Animation API to create various types of dynamic content.

Chapter 6, Styling Applications with CSS, outlines that JavaFX supports Cascading Style Sheets (CSS) to style applications similar to web pages.

Chapter 7, Building a Dynamic UI, reviews several JavaFX practices to build a modern adaptive UI.

Chapter 8, Effects, explains that effects such as a reflection or shadow are an essential part of modern applications.

Chapter 9, Media and WebView, showcases how JavaFX provides special controls dedicated to video, audio, and web content.

Chapter 10, Advanced Controls and Charts, reviews complex controls such as tables and charts.

Chapter 11, Packaging with Java9 Jigsaw, goes through the next step after writing an application—deploying it to end users. We will review JavaFX app building, packaging, and Jigsaw modularization options.

Chapter 12, 3D at a Glance, teaches us to create several small 3D applications and study JavaFX's 3D capabilities.

Chapter 13, What's Next?, looks at further options for mastering JavaFX.

To get the most out of this book

I hope you agree that we really need to write actual code to study programming. This book is built around code samples. Every section in the book is accompanied by a corresponding code sample and, if applicable, screenshots.

Before starting to read this book, I strongly encourage you to get a Git and download the accompanying GitHub repository, which you can find at https://github.com/sgrinev/mastering-javafx-9-10-book.

There are about 130 code samples, grouped by chapters numbers. For your convenience, each chapter is a NetBeans project, but almost every code sample is self-sufficient and can be run separately without the help of an IDE. If you opt for the latter approach, you can find the guidelines for running JavaFX apps from the command line inChapter 11, Packaging with Java9 Jigsaw.

At the time of writing, you need the latest in-development version of Netbeans to work with Java 9 and 10. You can find it at http://bits.netbeans.org/download/trunk/nightly/latest/.

While you can get a good grasp of the topics described by just reading the book and looking at the screenshots, toying with the code samples and seeing the results of your changes will give you a much better understanding of JavaFX APIs.

Also, although the book has been released once and for all, I plan to update and fix these samples if any issues are found later on. Refer to GitHub's README.mdfor a history of changes.

Download the example code files

You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.

You can download the code files by following these steps:

Log in or register at

www.packtpub.com

.

Select the

SUPPORT

tab.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box and follow the onscreen instructions.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR/7-Zip for Windows

Zipeg/iZip/UnRarX for Mac

7-Zip/PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-JavaFX-10. In case there's an update to the code, it will be updated on the existing GitHub repository.

We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots/diagrams used in this book. You can download it here:https://www.packtpub.com/sites/default/files/downloads/MasteringJavaFX10_ColorImages.pdf

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "You can import one CSS from another using the @import keyword."

A block of code is set as follows:

public static void main(String[] args) { // you custom code Application.launch(MyApplication.class, args);}

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

@DefaultProperty("children")

public class Paneextends Region

Any command-line input or output is written as follows:

> javac FXApplication.java

> java FXApplication

Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "For example, we see that the area under the mouse cursor is a DIV, as shown in the following screenshot."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.

Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Reviews

Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!

For more information about Packt, please visit packtpub.com.

Stages, Scenes, and Layout

During the last decade, user interfaces have evolved beyond the capabilities of the old Java technologies. Modern users want to work with visually appealing applications and are used to the rich user interfaces brought by Web 2.0 and smartphones.

To address that, JavaFX was envisioned and added to Java a few releases ago. It was created from scratch to avoid any backward compatibility issues, and with a great understanding of the needs of modern user interfaces.

In this book, we will review the most important JavaFX APIs and will look into resolving some of the most common problems that JavaFX developers face, based on my development experience and over 500 questions I've answered in the JavaFX section of stackoverflow.com.

In the first chapter, we will start with the backstage of a JavaFX application, including its windows and content area, and see which API is responsible for each of these main building blocks:

Application

: This handles the application workflow, initialization, and command-line parameters

Stage

: The JavaFX term for the window

Scene

: This is the place for the window's content

SceneGraph

: The content of the

Scene

At the end of the chapter, we will create a clock demo that will demonstrate the concepts from this chapter.

Application and JavaFX subsystems

The very first API, javafx.application.Application, represents the program itself. It prepares everything for us to start using JavaFX and is an entry point for all standalone JavaFX applications. It does the following:

Initializes JavaFX toolkit (subsystems and native libraries required to run JavaFX)

Starts JavaFX Application Thread (a thread where all UI work happens) and all working threads

Constructs the

Application

instance (which provides a starting point for your program) and calls the user-overridden methods

Handles application command line parameters

Handles all cleanup and shutdown once the application ends

Let's look closely at each of these steps.

Components of the JavaFX toolkit

JavaFX toolkit is the stuff hidden under the hood of the JavaFX. It's a set of native and Java libraries that handles all the complexity of the drawing UI objects, managing events, and working with various hardware. Luckily, they are well-shielded by the API from the user. We will have a brief overview of the major components. It can be useful, for example, during debugging your application; by knowing these component names, you will be able to identify potential problems from stack traces or error messages.