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

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

最佳答案

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

关于java - Java-keyTyped麻烦,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3786393/

10-16 12:44