NCSSS 2018 JavaFX Workshop

A Magical Mystery Treasure Hunt

Bring your mattock and your shovel. We are digging for buried treasure. There is a chain of interesting stuff to understand here. It is important to both understand and make the magic!

What is all of this magic? I shall deconstruct. There was no magic in putting the widgets in the window. That was easy and straightforward: create 'em and add 'em. Done.

Now let's talk about this black magic that makes these widgets "live.".

putText.setOnAction( e -> tf.setText("Hey look at me!"));
quitButton.setOnAction( e -> Platform.exit());

To figure this out, we must make a romp through the docs. First, we have a button. Go to that page. Make sure you get javafx.scene.control.Button, not java.awt.Button. That thar thang is passé.

Now let's find setOnAction. It is an inherited method from the parent class ButtonBase. This is the documentation on it.

public final void setOnAction(EventHandler<ActionEvent> value)

Sets the value of the property onAction.

Property description:

The button's action, which is invoked whenever the button is fired. This may be due to the user clicking on the button with the mouse, or by a touch event, or by a key press, or if the developer programmatically invokes the fire() method.

What the heck is an EventHandler<E>? First of all, notice that this is a generic interface with a type parameter; in this case it is of type ActionEvent. Notice the type bound on the type parameter; the parameter must be a subtype of type Event .

To continue our quest, we now go there.

Tombstone city! Of all things, this is an interface!!

But all is not lost; this argument type just specifies that this function will accept any object that is an instance of a class implementing this interface.

What about ActionEvent? This is not java.awt.event.ActionEvent; it's javafx.event.ActionEvent. This is an event that is fired when a button is pressed.

Time to dig some more!: What is this unholy business?

e -> tf.setText("Hey look at me!");
e -> Platform.exit();

Where is the actual object that implements EventHandler<ActionEvent> ?

First of all, these items are actually anonymous functions, or lambdas, a feature that came to be in Java8.

So, can a nameless function be an actual object? Yes. But there is some chicanery behind this. So, unafraid as we are, we are going there next.