2013-07-30 52 views
0

我想在使用TaskTimer的遊戲循環中做一個簡單的暫停功能,但它不起作用。任務計時器有問題嗎?我應該使用其他util嗎?我一直堅持這一段時間。TaskTimer不能在遊戲循環中工作

import java.awt.event.KeyEvent; 
import java.awt.event.KeyListener; 
import java.util.Timer; 
import java.util.TimerTask; 
import javax.swing.JFrame; 

public class test extends JFrame implements KeyListener, Runnable { 
    public boolean pause = false; 

    public test() { 
     new JFrame(); 
     addKeyListener(this); 
     setVisible(true); 
    } 

@Override 
public void run() { 
    // TODO Auto-generated method stub 

    while (true) { 
     if (pause) { 
      System.out.println("Paused"); 
      Timer timer = new Timer(); 
      timer.schedule(new TimerTask() { 
       public void run() { 
        System.out.println("Some Pause Related Task"); 
        pause = false; 
       } 
      }, (long) 3000); 
     } 
    } 
} 

@Override 
public void keyPressed(KeyEvent e) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void keyReleased(KeyEvent e) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void keyTyped(KeyEvent e) { 
    char c = e.getKeyChar(); 
    if (c == KeyEvent.VK_SPACE) { 
     System.out.println("typed space"); 
     pause = true; 
    } 
} 

public static void main(String[] args) { 
    new test(); 
} 
} 

回答

0

我建議您使用擺動計時器而不是實用程序計時器。它針對需要週期性回調的swing應用程序量身定製。回調數爲ActionListener,發生在美國東部時間。我也對構造函數中的new JFrame()行感到困惑。坦率地說,它是無用的。

0

您從不打電話run()啓動計時器。我還建議遵循tbodt的建議,以便在swing程序中使用swing Timers而不是通用定時器。

public void main() { 
    // Swing components should be modified only in the event dispatch thread. 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      test t = new test(); // test class should really be renamed to Test to follow java naming conventions 
      t.run(); 
     } 
    }); 
} 

此外,刪除while循環。否則,您會創建新的定時器,直到內存不足 - 您只需要一個定時器。計時器將負責重複。當您想要暫停時,請致電timer.stop()

-1

是啊使用正確的Timmer。這是一個常規任務,不打算控制主遊戲循環。現在更好地切換,以避免在以後的開發中出現TimerTask問題。爲什麼你不喜歡真相?如果你不相信閱讀這個API,但是你絕對不能掉以輕心。 ;)

1
  1. JFramefocusable JComponent S,也不會發生反應,KeyEvent,然後(從來沒有)KeyListener沒有作品,使用focusable JComponent(放在那裏JPanel是必需的,與setFocusable()),但不正確的可能途徑

  2. Swing JComponents均指定使用KeyBindings而不是低級KeyListener(在與KeyBindings比較其他副作用)

  3. 使用KeyListener只有在有三個或更多的Keys pressed e.i.的util.Timer

  4. 使用Swing Timer相反,從Swing Timer輸出通知EDT,否則你必須與Concurency in Swing

計算