Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Object Literals

In JavaFX, objects are instantiated using object literals. This is a declarative syntax using the name of the class that you want to create, followed by a list of initializers and definitions for this specific instance. In Listing 3.3, an object of class Title is created with the text “JavaFX is cool” at the screen position 10, 50. When the mouse is clicked, the provided function will be called.

Listing 3.3. Object Literal

var title = Title {
      text: "JavaFX is cool"
      x: 10
      y: 50
      onMouseClicked: function(e:MouseEvent):Void {
         // do something
      }
};

When declaring an object literal, the instance variables may be separated by commas or whitespace, as well as the semi-colon.

You can also override abstract functions within the object literal declaration. The following object literal, shown in Listing 3.4, creates an object for the java.awt.event.ActionListener interface and overrides the abstract java method void actionPerformed(ActionEvent e) method.

Listing 3.4. Object Literal – Override Abstract Function

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

var listener = ActionListener {
    override function
              actionPerformed(e: ActionEvent) : Void {
        println("Action Performed!");
    }
}
  • + Share This
  • 🔖 Save To Your Account