2015-03-08 66 views
4

我在Java中看到LWJGL庫的教程,但創建的窗口我會返回null。LWJGL:glfwCreateWindow return null

這是代碼:

import static org.lwjgl.glfw.GLFW.*; 
import static org.lwjgl.opengl.GL11.*; 
import static org.lwjgl.system.MemoryUtil.*; 
import java.nio.ByteBuffer; 
import org.lwjgl.glfw.GLFWvidmode; 

public class Main implements Runnable { 
    private int height = 720, width = height/9 * 16; 
    private String title = "Game"; 

    private Thread thread; 
    private boolean running = false; 

    private long window; 

    public void start() { 
     running = true; 
     thread = new Thread(this, title); 
     thread.start(); 
    } 

    private void init() { 
     if(glfwInit() != GL_TRUE) { 
      System.err.println("Non riesco ad inizializzare GLFW!"); 
      return; 
     } 

     glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); 
     glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); 
     glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); 
     glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); 
     glfwWindowHint(GLFW_RESIZABLE, GL_TRUE); 
     window = glfwCreateWindow(width, height, title, NULL, NULL); 

     if(window == NULL) { 
      System.err.println("Non riesco a creare una finestra GLFW!"); 
      return; 
     } 

     ByteBuffer vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor()); 
     glfwSetWindowPos(window, (GLFWvidmode.width(vidmode) - width)/2, (GLFWvidmode.height(vidmode) - height)/2); 

     glfwMakeContextCurrent(window); 
     glfwShowWindow(window); 
    } 

    @Override 
    public void run() { 
     init(); 
     while(running) { 
      update(); 
      render(); 

      if(glfwWindowShouldClose(window) == GL_TRUE) 
       running = false; 
     } 
    } 

    private void update() { 
     glfwPollEvents(); 
    } 

    private void render() { 
     glfwSwapBuffers(window); 
    } 

    public static void main(String[] args) { 
     new Main().start(); 
    } 
} 

返回以下錯誤:

Non riesco a creare una finestra GLFW! 
Exception in thread "Game" java.lang.NullPointerException 
    at org.lwjgl.system.Checks.checkPointer(Checks.java:66) 
    at org.lwjgl.glfw.GLFW.glfwSwapBuffers(GLFW.java:2546) 
    at com.michele.flappybird.Main.render(Main.java:66) 
    at com.michele.flappybird.Main.run(Main.java:54) 
    at java.lang.Thread.run(Unknown Source) 

我該如何解決?感謝任何人試圖幫助我。

+1

設置錯誤回調以獲取調試信息:GLFWErrorCallback errorCallback = Callbacks.errorCallbackPrint(); glfwSetErrorCallback(errorCallback);'' – javac 2015-06-03 15:52:21

回答

1

我的第一次嘗試是通過刪除Thread來簡化程序,因爲LWJGL有時會在主線程外部調用方法時出現問題。第二次嘗試將刪除glfwWindowHint(...)方法,而不是調用glfwDefaultWindowHints()

+1

您可能是指'glfwDefaultWindowHints()',雖然在這裏沒有必要。但我認爲你對線程是正確的:大多數GLFW函數需要在主線程上運行。另見[文檔](http://www.glfw.org/docs/latest/intro.html#thread_safety)。 – javac 2015-11-08 20:39:39