异常在Java中

问题描述:

import org.jsfml.window.*; 
import org.jsfml.graphics.*; 
import org.jsfml.internal.*; 
import org.jsfml.window.event.Event; 

public class Jsmql { 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) throws InterruptedException, ContextActivationException { 
     // TODO code application logic here 
     VideoMode vm = new VideoMode(100, 100); 
     Window fen = new Window(vm, "aaa"); 
     while(fen.isOpen()) { 
      fen.display(); 
      Event event = fen.pollEvent(); 
      if (event.type == Event.Type.CLOSED) { 
       fen.close(); 
      } 
     } 
    } 

} 

创建JSML窗口时,我想用Java创建与JSML Java的窗口(http://pdinklag.de/jsfml/) 我有下面的异常laucnhing我的代码时:在线程异常在Java中

异常“主” java.lang.NullPointerException在 jsmql.Jsmql.main(Jsmql.java:29) /Users/me/Library/Caches/NetBeans/8.1/executor-snippets/run.xml:53: Java返回:1 BUILD FAILED (总时间:0秒)

我看了Java NullPointerException的意义,但我没有成功解决我的问题。

+1

你确定你是运行这段代码?错误消息显示第29行,但您的代码段只有24行。 – lifeisfoo

+0

是的,错误是在行'if(event.type == Event.Type.CLOSED)' –

如果你看一下 Window.pollEvent() method的文档,你可以看到,它说:

回报目前在事件堆栈顶部的事件,或者返回null如果没有,则

所以你应该检查event不为空,访问其type属性之前:

if (event != null && event.type == Event.Type.CLOSED) { 
    fen.close(); 
}