gpt4 book ai didi

java - 关键事件发生时代码的执行顺序

转载 作者:行者123 更新时间:2023-12-02 03:05:10 24 4
gpt4 key购买 nike

我正在尝试用 Java 开发 Snake,并使用 KeyListeners 来获取按钮 w、a、s 和 d 的 KeyEvent。我创建了一个实现 KeyEvent 的类,并将该类的一个对象添加到我正在绘制的 Canvas 中。

游戏在 while(true) 循环中运行,在该循环内每秒调用 update() 方法 60 次,同时始终调用 render() 方法。

我现在的问题是关于 KeyEvent:如果我输入 f.x. w,我的 KeyEvent 对象中的方法是否立即执行,或者关于我正在运行的 while 循环,代码的执行顺序如何?在我的 while 循环中根本没有引用 KeyEvent 对象,但如果我键入一个 Key,KeyEvent 对象内的 Methode 就会被调用并执行其应该执行的操作。

我想说的是,我必须在 while(true) 循环中放置一个 if 语句,该语句将读取是否按下了任何按钮,或者 KeyListener 将在不同的线程上运行,它将在其中查找来自键盘处于 while(true) 循环中。

最佳答案

You posted no code, so we're forced to guess. The event listeners are executed on the Swing event dispatch thread. Your while loop is probably executing, concurrently, on the main thread or on a different thread.

docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

解决了答案。

关于java - 关键事件发生时代码的执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57027146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com