2013-05-13 43 views
1

我是Java新手,所以請原諒我尋求幫助,但經過4個小時尋找解決方案後,我真的變得絕望了。KeyListener不會關注

我目前正在設置遊戲並希望實現關鍵控件。我試圖通過KeyListenerKeyEventDispatcher來做到這一點,但我無法讓它工作。 KeyListener只是不會反應。我認爲應該使用它的方法有重點。

下面的代碼:

public class Sins extends JFrame implements KeyEventDispatcher { 

public boolean dispatchKeyEvent(KeyEvent e) { 
    if (e.getID() == KeyEvent.KEY_PRESSED) { 
     if(KeyEvent.VK_UP == e.getID()){ 
      System.exit(0); 
     } 

    } else if (e.getID() == KeyEvent.KEY_RELEASED) { 
      if(KeyEvent.VK_UP == e.getID()){ 
      System.exit(0); 
      } 
    } else if (e.getID() == KeyEvent.KEY_TYPED) { 
      if(KeyEvent.VK_UP == e.getID()){ 
      System.exit(0); 
      } 
    } 
    return false; 
} 

,這裏是在合作的地方是應該的方法:

public void run() { 

    setFocusable(true); 
    backgroundGraphics = (Graphics2D) background.getGraphics(); 
    long fpsWait = (long) (1.0/30 * 1000); 



requestFocusInWindow(); 

main: while (isRunning==true) { 
    long renderStart = System.nanoTime(); 

    KeyboardFocusManager manager = KeyboardFocusManager.getCurrentKeyboardFocusManager(); 
    manager.addKeyEventDispatcher(this); 

    x++; 
    requestFocusInWindow(); 

    // Update Graphics 
    do { 
     Graphics2D bg = getBuffer(); 

     if (isRunning == false) { 
      break main; 
     } 
     renderGame(backgroundGraphics); // this calls your draw method 

     if (scale != 1) { 
      bg.drawImage(background, 0, 0, width * scale, height 
        * scale, 0, 0, width, height, null); 
     } else { 
      bg.drawImage(background, 0, 0, null); 
     } 
     bg.dispose(); 

     requestFocusInWindow(); 


     this.requestFocus(); 

     if(x ==5000){ 
      isRunning=false; 
     } 

    } while (!updateScreen()); 

    // Better do some FPS limiting here 
    long renderTime = (System.nanoTime() - renderStart)/10000; 
    try { 
     Thread.sleep(Math.max(0, fpsWait - renderTime)); 
    } catch (InterruptedException e) { 
     Thread.interrupted(); 
     break; 
    } 


    renderTime = (System.nanoTime() - renderStart)/10000; 

    } 

    this.dispose(); 
    System.exit(0); 
} 

程序計數到5000。試驗後,目前正在關閉本身我試圖通過向上按鈕關閉它,但它不會以這種方式關閉。 我真的很感謝一些幫助,因爲我說我是Java新手。

+0

不知道你怎麼連得到這個編譯。例如。我不知道'main:'應該在你的代碼中做什麼。 – 2013-05-13 21:12:32

+0

好吧,如果isRunning = false,它應該通過破壞來「停止」方法,我打算稍後使用它來停止遊戲。 – user2379129 2013-05-13 21:15:46

+1

@ b1naryatr0phy它是一個標籤。想想它就像是一個goto,然後明白你爲什麼不應該知道它) – MadProgrammer 2013-05-13 21:56:29

回答

1

你遇到的第一個問題是KeyListener是一個衆所周知的和有據可查的文件(尤其是SO)。 KeyListener只有在它們所連接的組件可以聚焦且具有鍵盤焦點時纔會響應。想想一個文本字段,當它沒有焦點時,它不會更新。

你的第二個問題是使用KeyBoardFocusManager,這只是矯枉過正的問題。

相反,你應該利用[按鍵綁定] API,這是簡單的有監控的KeyBoardFocusManager,更可靠然後KeyListeners

+0

這不起作用,程序的所有其他部分將會識別按鍵是否被按下,但只要運行方法被調用,它不再起作用 – user2379129 2013-05-14 15:03:23

+0

我現在有解決方案,我現在使用一個新線程來運行運行方法。 – user2379129 2013-05-14 17:18:43

+0

所以現在你可能會違反事件調換線程 – MadProgrammer 2013-05-14 21:11:08