Tutorials‎ > ‎

Handling Native Java Arrays in JavaFX


The Sequence type, in JavaFX, lets developers aggregate a collection of objects backed by a list-like data structure.  Sequence was designed to be a container of sequentially-indexed arbitrary items (number, strings, nodes, user-defined types, and so on).  While a sequence expression looks like the traditional array, sequences, however, are not treated as arrays and are incompatible to native Java arrays.  

Native Java Arrays in JavaFX
If you want to share arrays between JavaFX and Java, you are in luck.  JavaFX supports the notion native arrays expressed using the format 'nativearray of {type}'.  The following shows some examples of nativearray declarations:

def numbers = [0,1,2,3,4,5,6,7,8,9,10] as nativearray of Integer;
def days  = ["Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat"] as nativearray of String;
def chars = [0xAB, 0xCD, 0xEF] as nativearray of Byte;

Similar to the Sequence type, native arrays can be traversed using the for-loop expression.  The following code snippet returns a nativearray slice of even numbers from the original array:

def evens = for(even in numbers where even mod 2 == 0){even}

Using Java IO API
The following shows how to use nativearray type to write an array of bytes to a file using a FileOutputStream:


import com.sun.javafx.io.File;
import java.lang.RuntimeException;
import java.io.FileOutputStream;


def stream = new FileOutputStream(new java.io.File("./data-file.txt"));;
def data:nativearray of Byte = "This is data for the file".getBytes();
stream.write(data);
stream.close();


All code/recipes are based on the JavaFX Application Cookbook published by Packt Publishing. Get access to over 80 recipes covering a wide variety of topics from the fundamentals to the advanced recipes.

Click here to get your copy!