簡體   English   中英

轉換類將ActionListener實現為線程

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM