2010-09-24 50 views
0

當我嘗試運行我的程序並按下某個鍵時,我總是收到相同的錯誤。Java - keyTyped疑難問題

錯誤表明問題出在keyTyped函數中,但對我來說看起來不錯。

您怎麼看?

代碼:

//Key Listener. 
private class GameKeyListener implements KeyListener { 
public void keyTyped (KeyEvent event) { 
    char inputKey = 'd'; 
    if(isStart == true){ 
    try{ 
    inputKey = event.getKeyChar(); 
    } catch(Exception e){ 
    System.out.println("Bad input."); 
    } 
    if(inputKey == 's'){ 
    isStart = false; 
    timer.start();  // Add timer. Start game here. 
    } 
    } 
} 
public void keyPressed (KeyEvent event) {}; 
public void keyReleased (KeyEvent event){}; 
} 

錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException 
at RoofRunnerGame$GameKeyListener.keyTyped(RoofRunnerGame.java:106) 
at java.awt.Component.processKeyEvent(Component.java:6303) 
at java.awt.Component.processEvent(Component.java:6125) 
at java.awt.Container.processEvent(Container.java:2085) 
at java.awt.Window.processEvent(Window.java:1836) 
at java.awt.Component.dispatchEventImpl(Component.java:4714) 
at java.awt.Container.dispatchEventImpl(Container.java:2143) 
at java.awt.Window.dispatchEventImpl(Window.java:2478) 
at java.awt.Component.dispatchEvent(Component.java:4544) 
at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1850) 
at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:712) 
at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:990) 
at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:855) 
at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:676) 
at java.awt.Component.dispatchEventImpl(Component.java:4586) 
at java.awt.Container.dispatchEventImpl(Container.java:2143) 
at java.awt.Window.dispatchEventImpl(Window.java:2478) 
at java.awt.Component.dispatchEvent(Component.java:4544) 
at java.awt.EventQueue.dispatchEvent(EventQueue.java:635) 
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296) 
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211) 
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196) 
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188) 
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122) 

回答

1

我覺得一個變量是不正確的線路106也許timer初始化?

0

在行

timer.start();  // Add timer. Start game here 

你確定計時器沒有null