【问题标题】:Convert class implements ActionListener into thread将类实现 ActionListener 转换为线程
【发布时间】:2013-08-01 02:48:08
【问题描述】:

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

【问题讨论】:

  • 可以实现多个接口,实现Runnable。实现 ActionLister、Runnable{}
  • 这取决于,ActionListener 实际上是做什么的?您可能需要阅读 Concurrency in Swing 以了解 Swing 和 Threads 的一些问题
  • @MadProgrammer ActionListener 获取击键并在屏幕上移动精灵。
  • @arynaq 谢谢,这回答了我的问题。

标签: java swing timer actionlistener multiple-inheritance


【解决方案1】:

不要将您的 UI 与其他游戏组件捆绑在一起。您需要很好地分离关注点。考虑拥有一个代表游戏中所有事物的类,这就是您的游戏状态。你的 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
    }

  }
}

【讨论】:

  • 这很有帮助。不能完全回答我的问题,但它让我找到了更好的方法。
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 2016-10-29
    • 2017-02-16
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多