使用JavaFX调整每秒的执行次数 [英] Regulating the number of executions per second using JavaFX

查看:1218
本文介绍了使用JavaFX调整每秒的执行次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我正在使用JavaFX实现Conway的生命游戏。简而言之,在我的类中扩展AnimationTimer,在handle()方法中,它遍历2D数组中的每个单元格,并更新每个位置,然后使用2D数组中的信息绘制到画布。

So as of right now I'm implementing Conway's Game of Life using JavaFX. In a nutshell, in my class extending AnimationTimer, within the handle() method, it traverses through every cell in a 2D array and updates each position, then draws to the canvas using the information in the 2D array.

这工作完全正常,但问题是它运行太快。你不能真正看到画面上发生了什么。在窗口上我有画布以及几个按钮。我添加了一个Thread.sleep(1000)试图调节一代/帧每秒,但这样做导致窗口不能立即检测到按钮按下。按钮按下是完全响应,当没有告诉线程睡觉。

This works completely fine but the problem is it runs far too fast. You can't really see what's going on on the canvas. On the window I have the canvas as well as a few buttons. I added a Thread.sleep(1000) to try to regulate a generation/frame per second, but doing this causes the window to not detect the button presses immediately. The button presses are completely responsive when not telling the thread to sleep.

有人对如何解决这个问题有任何建议吗?

Does anyone have any suggestions on how to solve this?

推荐答案

您可以使用 时间表 这可能更适合这个。将循环计数设置为 Animation.INDEFINITE ,并在更新之间添加 KeyFrame code> handle 实现为框架的 onFinished

You can use Timeline which is probably more suitable for this. Set cycle count to Animation.INDEFINITE, and add a KeyFrame with the delay you want between updates, and your current handle implementation as the frame's onFinished.

final Timeline timeline = new Timeline();
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.getKeyFrames().add(
        new KeyFrame(
                Duration.seconds(1), 
                event -> handle()
        )
);
timeline.play();

或者,您可以尝试延迟 KeyFrame 为零,并使用时间轴的 targetFrameRate ,但我个人从未尝试过。

Alternatively, you may try to have the delay of the KeyFrame as zero, and use the Timeline's targetFrameRate, but I personally never tried it.

另一个选择是在 AnimationTimer 中保留 frameSkip 变量:

Another option is to keep a frameSkip variable in your AnimationTimer:

private int frameSkip = 0;
private final int SKIP = 10;

@Override
public void handle(long now) {
    frameSkip++;
    if (frameSkip <= SKIP) {
        // Do nothing, wait for next frame;
        return;
    }
    // Every SKIP frames, reset frameSkip and do animation
    frameSkip = 0;

    // Do animation...
}

这篇关于使用JavaFX调整每秒的执行次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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