Java - keyTyped麻烦

时间:2010-09-24 11:04:06

标签: java user-interface keylistener

当我尝试运行程序并按下某个键时,我一直收到同样的错误。

错误表明问题出在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)

2 个答案:

答案 0 :(得分:1)

我认为变量未在第106行正确初始化。也许timer

答案 1 :(得分:0)

在第

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

你确定计时器不是null吗?