tags:

views:

22

answers:

1

Following is a code fragment. I am updating a rectangle using a for loop when a button is pressed. This is a model for my ultimate intention of showing visualization of data model as it changes large number of times inside a for loop. It works but I see only one change. Now since I am changing the width randomly I should see large number of changes. It seems I am making a wrong assumption on something basic.

The code goes below:

 7 var rec: Rectangle = Rectangle {

 8             x: 10, y: 10
 9             width: 140, height: 90
10             fill: Color.BLACK
11         }
12 
13 Stage {

14     title: "MyApp"
15     scene: Scene {
16         width: 200
17         height: 200
18         content: [

19             rec,
20             Button {
21                 text: "Button"
22                 action: function () {

23                     for (i in [1..999]) {
24                         rec.width = 25 + java.lang.Math.random()*50;
25                     }
26                 }

27             }
28         ]
29     }
30 }
+1  A: 

It looks like what is happening is that the changes happen so fast that the Scene graph updates can't keep up and you just don't see them until the last update.

I would suggest refactoring as follows which gives you slightly more control (you can update the refresh rate as you see fit, as well as start and stop the animation as you wish).

var rec: Rectangle = Rectangle {
             x: 10, y: 10
             width: 140, height: 90
             fill: Color.BLACK
         }


var timeline = Timeline {
    repeatCount: 20
    keyFrames : [
        KeyFrame {
            time : 100ms
            canSkip : true
            action: function(): Void {
                rec.width = 25 + java.lang.Math.random()*50;
            }
        }
    ]
}

Stage {
     title: "MyApp"
     scene: Scene {
         width: 200
         height: 200
         content: [
             rec,
             Button {
                 text: "Button"
                 action: function () {
                    timeline.playFromStart();
                 }
             }
         ]
     }
}
Matthew Hegarty
Technically, it is not <b>that the Scene graph updates can't keep up</b>. It is that the runtime will coalesce the update events for performance. However, your timeline solution is the right answer for the problem.
JimClarke