In the Binding to a Sequence in Compiled JavaFX Script article, we bound a ListBox to a sequence in the model. This binding causes the ListBox to stay in sync with the sequence. The example in today's article builds on the previous one, introducing the concept of sequence triggers. Here's a screenshot of the program, followed by the source code. I'll follow up with a brief discussion.
/*
* SequenceTriggers.fx
*
* Developed 2008 by James L. Weaver (jim.weaver at lat-inc.com)
* to serve as a JavaFX Script example of using sequence triggers
*/
import javafx.ui.*;
import java.lang.System;
class Model {
attribute entries:String[] = ["Red", "Green", "Blue", "Yellow", "Purple"]
on replace oldValue[idxA..idxB] = newElement {
System.out.println("replaced {oldValue} at {idxA} with {entries[idxA]}");
};
attribute selectedIndex:Integer = 0 on replace {
System.out.println("selectedIndex={selectedIndex}");
};
attribute enteredText:String;
}
Frame {
var mdl = Model {}
title: "Sequence Triggers"
width: 400
height: 200
background: Color.WHITE
visible: true
content:
BorderPanel {
center:
FlowPanel {
content:
ListBox {
cells: bind for (entry in mdl.entries)
ListCell {
text: entry
}
selection: bind mdl.selectedIndex with inverse
fixedCellWidth: 100
visibleRowCount: 4
}
}
bottom:
FlowPanel {
content: [
TextField {
value: bind mdl.enteredText with inverse
columns: 10
},
Button {
text: "Insert"
defaultButton: true
enabled: bind mdl.enteredText.trim() <> ""
action:
function():Void {
insert mdl.enteredText before mdl.entries[mdl.selectedIndex.intValue()];
mdl.enteredText = "";
System.out.println("sizeof entries={sizeof mdl.entries}");
}
},
Button {
text: "Replace"
enabled: bind mdl.enteredText.trim() <> ""
action:
function():Void {
mdl.entries[mdl.selectedIndex.intValue()] = mdl.enteredText;
mdl.enteredText = "";
}
},
Button {
text: "Delete"
enabled: bind mdl.selectedIndex >= 0
action:
function():Void {
delete mdl.entries[mdl.selectedIndex.intValue()];
}
}
]
}
}
}
Sequence Triggers
Triggers can be created that execute when certain operations happen to a sequence. These operations are:
- Inserting a slice
- Replacing a slice
- Deleting a slice
Note that a slice is a contiguous portion of a sequence, which can consist of one or more elements. The program example above demonstrates the use of each of these operations, which are now handled exclusively by the replace trigger. Notice the distinction between the replace trigger that applies to slices of a sequence, and the replace trigger that applies to attributes (as shown in the selectedIndex attribute declaration).
For an in-depth explanation of of sequence replace triggers and slices, please see a writeup on the subject from the JavaFX Compiler team.
0 comments:
Post a Comment