如何在 Java 中监听按键时使图像移动。
我开始学习java编程,我认为通过游戏开发来学习java很酷。我知道如何绘制图像并听按键然后移动该图像。但是,当窗口监听按键时,是否可以使图像在窗口中来回移动?例如,当图像或物体(如宇宙飞船)在窗口中从左向右移动时,如果我按空格键,激光将在屏幕底部发射(酷哈:D)。但基本上我只想知道如何在窗口监听按键时使图像从左向右移动。
我想我将在窗口中添加一个关键侦听器,然后触发无限循环来移动图像。或者我是否需要学习线程以便另一个线程可以移动对象?
请指教。
非常感谢。
I'm starting to learn java programming and I think it's cool to learn java through game development. I know how to draw image and listen to a keypress then move that image. But is it possible to make the image move back and forth to the window while the window is listening to a keypress? Like for example, while the image or object(like spaceship) is moving left to right in the window, then if I press space key, a laser will fire at the bottom of the screen( cool huh :D ). But basically I just want to know how to make the image move left to right while the window is listening to a keypress.
I'm thinking that I will add a key listener to my window then fire an infinite loop to move the image. Or do I need to learn about threading so that another thread will move the object?
Please advise.
Many thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,Swing Timer 和按键绑定效果很好。这是另一个例子(我的):)
这是使用此精灵表的另一个示例:
从 此网站。
这又是一个在 JPanel 的 PaintComponent 方法中绘图并使用键绑定来告知移动方向的示例。
Yep, a Swing Timer and Key Bindings would work well. Here's another example (mine) :)
Here is another example that uses this sprite sheet:
obtained from this site.
Again it's an example of drawing within a JPanel's paintComponent method and using Key Bindings to tell which direction to move.
作为
KeyListener
的替代方案,请考虑使用 < em>操作和键绑定,此处进行了讨论。源自此示例,下面的程序使用按钮或按键向左、向下、向上或向右移动一行。As an alternative to
KeyListener
, consider using actions and key bindings, discussed here. Derived from this example, the program below moves a line left, down, up or right using either buttons or keys.您可以使用 Swing Timer 来制作图像动画:
您可以将 KeyListener 添加到面板,它将独立于图像动画。
You can use a Swing Timer to animate an image:
You can add a KeyListener to the panel and it will operate independently of the image animation.