[英]Convert class implements ActionListener into thread
我有一个简单的2D游戏类,如下所示:
public class Game extends JPanel implements ActionListener {
private Timer timr;
public Game(){
//other stuff
timr = new Timer(10, this);
timr.start();
}
//other methods including ActionListener-related ones
}
而不是使用Timer()作为我想作为线程运行Game的时间,我该如何做并保留ActionListener函数?
不要将用户界面与其他游戏组件捆绑在一起。 您需要将关注点分开。 考虑让一个类拥有您游戏中所有事物的表示,这就是您的游戏状态 。 您的UI应该只关注绘制当前游戏状态。 您的游戏应在循环中运行,在该循环中更新游戏状态,然后使用UI进行渲染。
class Game() {
World world; //holds state of things in game
UI ui;
long time;
long elapsed; //number of ms since last update
mainGameLoop() {
time = System.currentTimeInMillis();
while (gameRunning()) {
elapsed = System.currentTimeInMillis() - time;
time = System.currentTimeInMillis();
world.update(elapsed); //updates game state
ui.render(world); //draws game state to screen
}
}
}
因此,正如@arynaq所评论的,可以通过将逗号放在下一个抽象类前面,然后再插入抽象方法来实现多次。
class Foo extends JPanel implements ActionListener, Runnable{
//runnable methods
public void run(){}
//ActionListener methods
public void actionPerformed(){}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.