Java Reference
In-Depth Information
There's more...
Using a custom data model with ListView
While the previous code shows you how to use String sequences as the data model for a
ListView, you are not limited to that. Here, we are going to modify the previous example to use
a custom data model as the list item. The full listing of the code presented here can be found
at
ch04/source-code/src/controls/ListViewDemoExtended.fx
.
To use a custom data model with the ListView, we use the following steps:
1. Define the model class. Below, we create class
MyItem
as the one to be used in the
ListView instance. Make sure to override the function
toString()
to return a string
representation of the data item to be displayed in the list. The
MyItem
class stores a
shape along with a descriptive name.
class
MyItem
{
public var id:Integer = new Random().nextInt(100);
public var name:String;
public var shape:Shape;
override function toString
():String {
"Shape: {%5s name}"
}
}
2. Add instances of the model to the
ListView.items
property. Here, we add four
instances of the
MyItem
class to the ListView. Each
MyItem
instance has an id,
name, and a shape stored in it.
var listView = ListView {
width:200
height:150
items
: [
MyItem
{id:1 name: "Rectangle"
shape:Rectangle{width:100 height:50}}
MyItem
{id:2 name:"Circle" shape:Circle{radius:25}}
MyItem
{id:3 name:"Line"
shape:Line{startX:10 startY:10 endX:40 endY:50}}
MyItem
{id:4 name:"Round Rectangle"
shape:Rectangle{
width:100 height:50
arcHeight:10 arcWidth:10}
}
]
}


