Home > Articles > Programming > Java

A Taste of JavaFX

This chapter is from the book

This chapter is from the book

2.4 Key JavaFX Features

GuitarTuner is a fairly typical JavaFX example application. It has a graphical representation and responds to user input by changing some of its visual properties (as well as producing guitar sounds). Let’s look at some of the key JavaFX features it uses to give you a broad look at the language.

Type Inference

JavaFX provides def for read-only variables and var for modifiable variables.

	def numberFrets = 2;							// read-only Integer
	var x = 27.5;									// variable Number
	var y: Number;									// default value is 0.0
	var s: String;
// default value is ""

The compiler infers types from the values you assign to variables. Read-only numberFrets has inferred type Integer; variable x has inferred type Number (Float). This means you don’t have to specify types everywhere (and the compiler tells you when a type is required.)

Strings

JavaFX supports dynamic string building. Curly braces { } within a String expression evaluate to the contents of the enclosed variable. You can build Strings by concatenating these String expressions and String literals. For example, the following snippet prints "Greetings, John Doe!".

	def s1 = "John Doe";		
	println("Greetings, {s1}!");			// Greetings, John Doe!

Shapes

JavaFX has numerous shapes that help you create scene graph nodes. There are shapes for creating lines (Line, CubicCurve, QuadCurve, PolyLine, Path) and shapes for creating geometric figures (Arc, Circle, Ellipse, Rectangle, Polygon). The GuitarTuner application uses only Rectangle and Line, but you’ll see other shape examples throughout this book.

Let’s look at shapes Rectangle and Circle. They are both standard JavaFX shapes that extend class Shape (in package javafx.scene.shape). You define a Circle by specifying values for its radius, centerX, and centerY properties. With Rectangle, you specify values for properties height, width, x, and y.

Shapes share several properties in common, including properties fill (type Paint to fill the interior of the shape), stroke (type Paint to provide the outline of the shape), and strokeWidth (an Integer for the width of the outline).

Here, for example, is a Circle with its center at point (50,50), radius 30, and color Color.RED.

	Circle {
		radius: 30  
		centerX: 50 
		centerY: 50	
		fill: Color.RED
	}

Here is a Rectangle with its top left corner at point (30, 100), height 30, width 80, and color Color.BLUE.

	Rectangle {
		x: 30, y: 100
		height: 30, width: 80
		fill: Color.BLUE
	}

All shapes are also Nodes (javafx.scene.Node). Node is an all-important class that provides local geometry for node elements, properties to specify transformations (such as translation, rotation, scaling, or shearing), and properties to specify functions for mouse and key events. Nodes also have properties that let you assign CSS styles to specify rendering.[1] We discuss graphical objects in detail in Chapter 4.

Sequences

Sequences let you define a collection of objects that you can access sequentially. You must declare the type of object a sequence will hold or provide values so that its type can be inferred. For example, the following statements define sequence variables of GuitarString and Rectangle objects.

	var guitarStrings: GuitarString[];
	var rectangleSequence: Rectangle[];

These statements create read-only sequences with def. Here, sequence noteValues has an inferred type of Integer[]; sequence guitarNotes has an inferred type of String[].

	def noteValues = [ 40,45,50,55,59,64 ];
	def guitarNotes = [ "E","A","D","G","B","E" ];

Sequences have specialized operators and syntax. You will use sequences in JavaFX whenever you need to keep track of multiple items of the same object type. The GuitarTuner application uses a sequence with a for loop to build multiple Line objects (the frets) and GuitarString objects.

		// Build Frets
		for (i in [0..<numberFrets])
			Line { . . . }

		// Build Strings
		for (i in [0..<numberStrings])
			GuitarString { . . . }

The notation [0..<n] is a sequence literal and defines a range of numbers from 0 to n-1, inclusive.

You can declare and populate sequences easily. The following declarative approach inserts Rectangles into a sequence called rectangleSequence, stacking six Rectangles vertically.

		def rectangleSequence = for (i in [0..5])
			Rectangle {
				x: 20
				y: i * 30
				height: 20
				width: 40
			}

You can also insert number values or objects into an existing sequence using the insert operator. The following imperative approach inserts the six Rectangles into a sequence called varRectangleSequence.

		var varRectangleSequence: Rectangle[];
		for (i in [0..5])
			insert Rectangle {
				x: 20
				y: i * 30
				height: 20
				width: 40
			} into varRectangleSequence;

You’ll see more uses of sequence types throughout this book.

Calling Java APIs

You can call any Java API method in JavaFX programs without having to do anything special. The GuitarString node “plays a note” by calling function noteOn found in Java class SingleNote. Here is GuitarString function playNote which invokes SingleNote member function noteOn.

	function playNote(): Void {
		synthNote.noteOn(note);			// nothing special to call Java methods
		vibrateOn();
	}

Class SingleNote uses the Java javax.sound.midi package to generate a synthesized note with a certain value (60 is “middle C”). Java class SingleNote is part of project GuitarTuner.

Extending CustomNode

JavaFX offers developers such object-oriented features as user-defined classes, overriding virtual functions, and abstract base classes (there is also “mixin” inheritance). GuitarTuner uses a class hierarchy with subclass GuitarString inheriting from a JavaFX class called CustomNode, as shown in Figure 2.4.

This approach lets you build your own graphical objects. In order for a custom object to fit seamlessly into a JavaFX scene graph, you base its behavior on a special class provided by JavaFX, CustomNode. Class CustomNode is a scene graph node (a type of Node, discussed earlier) that lets you specify new classes that extend from it. Just like Java, “extends” is the JavaFX language construct that creates an inheritance relationship. Here, GuitarString extends (inherits from) CustomNode. You then supply the additional structure and behavior you need for GuitarString objects and override any functions required by CustomNode. JavaFX class constructs are discussed in more detail in Chapter 3 (see “Classes and Objects”).

Here is some of the code from GuitarTuner's GuitarString class. The create function returns a Node defining the Group scene graph for GuitarString. (This scene graph matches the node structure in Figure 2.2 and Figure 2.3. Listing 2.2 on page 38 shows the create function in more detail.)

	public class GuitarString extends CustomNode {
		// properties, variables, functions
		. . . 
		protected override function create(): Node {
			return Group {
				content: [
					Rectangle { ... }
					Rectangle { ... }
					Rectangle { ... }
					Text { ... }
				]
			}	// Group
		}
	}	// GuitarString

Geometry System

In JavaFX, nodes are positioned on a two-dimensional coordinate system with the origin at the upper-left corner. Values for x increase horizontally from left to right and y values increase vertically from top to bottom. The coordinate system is always relative to the parent container.

Layout/Groups

Layout components specify how you want objects drawn relative to other objects. For example, layout component HBox (horizontal box) evenly spaces its subnodes in a single row. Layout component VBox (vertical box) evenly spaces its subnodes in a single column. Other layout choices are Flow, Tile, and Stack (see “Layout Components”). You can nest layout components as needed.

Grouping nodes into a single entity makes it straightforward to control event handling, animation, group-level properties, and layout for the group as a whole. Each group (or layout node) defines a coordinate system that is used by all of its children. In GuitarTuner, the top level node in the scene graph is a Group which is centered vertically within the scene. The subnodes are all drawn relative to the origin (0,0) within the top-level Group. Centering the Group, therefore, centers its contents as a whole.

JavaFX Script Artifacts

Defining the Stage and Scene are central to most JavaFX applications. However, JavaFX scripts can also contain package declarations, import statements, class declarations, functions, variable declarations, statements, and object literal expressions. You’ve already seen how object literal expressions can initialize nodes in a scene graph. Let’s discuss briefly how you can use these other artifacts.

Since JavaFX is statically typed, you must use either import statements or declare all types that are not built-in. You’ll typically define a package and then specify import statements. (We discuss working with packages in Chapter 3. See “Script Files and Packages.”) Here is the package declaration and import statements for GuitarTuner.

	package guitartuner;

	import javafx.scene.effect.DropShadow;
	import javafx.scene.paint.Color;
	import javafx.scene.paint.LinearGradient;

		. . . more import statements . . .

	import javafx.stage.Stage;
	import noteplayer.SingleNote;

If you’re using NetBeans, the IDE can generate import statements for you (type Ctrl+Shift+I in the editor window).

You’ll need script-level variables to store data and read-only variables (def) for values that don’t change. In GuitarTuner, we define several read-only variables that help build the guitar strings and a variable (singleNote) that communicates with the Java midi API. Note that noteValues and guitarNotes are def sequence types.

	def noteValues = [ 40,45,50,55,59,64 ];
	def guitarNotes = [ "E","A","D","G","B","E" ];
	def numberFrets = 2;
	def numberStrings = 6;
	var singleNote =  SingleNote { };

When you declare a Stage, you define the nested nodes in the scene graph. Instead of declaring nodes only as object literal expressions, it’s also possible to assign these object literals to variables. This lets you refer to them later in your code. (For example, the Scene object literal and the Group object literal are assigned to variables in order to compute the offset for centering the group vertically in the scene.)

	var scene: Scene;
	var group: Group;

	scene: scene = Scene { ... }
	group = Group { ... }

You may also need to execute JavaFX script statements or define utility functions. Here’s how GuitarTuner makes the SingleNote object emit a “guitar” sound.

	singleNote.setInstrument(27);           // "Clean Guitar"

Once you set up the Stage and scene graph for an application, it’s ready to ready to run.[2] In GuitarTuner, the application waits for the user to pluck (click) a guitar string.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020