Home > Articles > Programming > Java

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account