使用javafx使用for循环更新场景中的形状 [英] updating a shape in scene with a for loop using javafx

查看:202
本文介绍了使用javafx使用for循环更新场景中的形状的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码片段。当按下按钮时,我使用for循环更新矩形。这是一个模型,我的最终目的是显示数据模型的可视化,因为它在for循环中变化了很多次。它有效,但我只看到一个变化。现在,因为我随机改变宽度,我应该看到大量的变化。我似乎对基本的东西做了错误的假设。

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.

代码如下:


 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 }


推荐答案

看起来发生的事情是变化发生的速度太快,以至于场景图更新无法跟上,你只是看不到它们直到最后一次更新。

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();
                 }
             }
         ]
     }
}

这篇关于使用javafx使用for循环更新场景中的形状的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆