Convert类将ActionListener实现为线程

时间:2013-08-01 02:48:08

标签: java swing timer actionlistener multiple-inheritance

我有一个简单的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函数?

2 个答案:

答案 0 :(得分:1)

不要将UI与其他游戏组件捆绑在一起。你需要很好地分离关注点。考虑拥有一个包含游戏中所有内容表示的类,这是您的游戏 state 。你应该只关注绘制当前游戏状态的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
    }

  }
}

答案 1 :(得分:0)

正如@arynaq评论的那样,可以通过在下一个抽象类之前放一个逗号来实现多次,然后插入抽象方法。

class Foo extends JPanel implements ActionListener, Runnable{
    //runnable methods
    public void run(){}

    //ActionListener methods
    public void actionPerformed(){}
}