为什么我可以向JPanel添加多个对象?
当我添加到游戏屏幕上时,多个鸭子的对象只有一个在屏幕上出现。当我在Games屏幕类中添加鸭外构造函数时,我有许多鸭子对象,但是这种鼠标的方法不起作用。
When I add to the GameScreen more than one Object of class Duck only one appears on the screen. When I add Duck outside constructor in GameScreen class I have many Object of Duck but then the mouseClicked method doesn't work on Duck.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看如何使用borderlayout 。
BorderLayout
将仅显示添加到任何单个位置的最后一个组件。话虽如此,我不认为这是您真正想进入的方向。相反,以单个
jpanel
开始并覆盖其paintcomponent
方法,然后渲染全部您直接通过游戏对象。组件是具有很大复杂性的重物,通常不适合这种操作。另外,您也不需要3个以上的线程(swing
计时器
s使用线程将调用安排回UI)。使用单个秋千计时器
作为您的“主游戏循环”,该循环应负责更新状态和调度油漆通过。摆动不是线程安全的,因此建议使用螺纹
更新标签。从中,您可以根据需要开始添加更多实体,例如,我可以修改
main
方法,以包括很多鸭子...显然这是并且过于简化示例仅作为核心概念的演示,您需要对基本游戏开发和2D图形进行更多研究。
Take a look at How to Use BorderLayout.
BorderLayout
will only present the last component added to any single position.Having said that, I don't think this is the direction you really want to head in. Instead, start with a single
JPanel
and override itspaintComponent
method, then render all you game objects directly through. Components are heavy objects with a lot of complexity and aren't generally well suited for this kind of operation.Also, you also don't need 3+ threads (Swing
Timer
s make use of a thread to schedule calls back to the UI). Use a single SwingTimer
as your "main game loop", which should be responsible for updating the state and scheduling paint passes. Swing is not thread safe, so the use of theThread
to update the label is ill advised.From this, you can start adding more entities as needed, for example, I can modify the
Main
method to include LOTs of ducks...This is obviously and overly simplified example intended only as a demonstration of core concept, you'll need to do more research into basic game development and 2D graphics.