使用JavaFX调整每秒的执行次数-开发者之家

您所在的位置:网站首页 javafx窗口切换 使用JavaFX调整每秒的执行次数-开发者之家

使用JavaFX调整每秒的执行次数-开发者之家

2023-03-27 22:14| 来源: 网络整理| 查看: 265

问题描述

到目前为止,我正在使用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


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3