我正在嘗試使用NetBeans和Swing的一個非常簡單的JOGL教程,它似乎不管我如何安排事情,我總是收到一個空指針異常。這裏是我使用的代碼(改編自教程):簡單的JOGL測試用例中的NullPointerException
package testjogl;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLCanvas;
import java.awt.Dimension;
public class OpenGLTest extends javax.swing.JFrame implements GLEventListener {
public OpenGLTest() {
initComponents();
}
public void doMain() {
GLCanvas canvas = new GLCanvas();
canvas.addGLEventListener(this);
canvas.setPreferredSize(new Dimension(640, 480));
this.getContentPane().add(canvas); // <--- This is where the exception happens
this.pack();
this.setVisible(true);
}
@Override
public void init(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
}
@Override
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { }
@Override
public void display(GLAutoDrawable drawable) {
GL2 gl = drawable.getGL().getGL2();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
}
@Override
public void dispose(GLAutoDrawable drawable) { }
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new OpenGLTest().doMain();
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}
在那裏我的畫布添加到我的表格行,我得到:在陽光打 異常顯示java.lang.NullPointerException(空)斷點.awt.image.OffScreenImageSource由線程AWT-EventQueue-0執行。
我已經嘗試了幾個不同的JOGL教程,當我將畫布添加到表單時,它們都保持拋出此異常。我找不到OffScreenImageSource的代碼,但是當我逐步完成時,它在Container.java的第1119行中停止。代碼是:
invalidateIfValid();
if (peer != null) {
comp.addNotify(); // <---- Dies right here
}
有沒有人有任何想法,可能是什麼原因造成這種情況?
我無法重現這個問題,但是......除了已經給出的答案之外,還有一個瘋狂的猜測:在將畫布添加到內容窗格之前嘗試添加另一個this.pack()調用** 。 (這將「實現」框架,並應分配所有內部資源 - 也就是似乎爲空的「comp」)。 – Marco13
@ Marco13:謝謝!這導致我發現問題。我設置了一個NPE斷點。顯然,代碼會拋出一個NPE,然後捕獲並忽略它。我很困惑,因爲如果你忽略NPE,我發佈的代碼仍然沒有任何作用。但是,我發現如果我添加「canvas.setBounds(new Rectangle(0,0,640,480));」創建畫布後的任何地方,事情開始工作。我不確定爲什麼這是必要的,或者爲什麼沒有教程提到它,但這已經爲我解決了一些問題。謝謝! – TrespassersW
這實際上可能與尺寸爲(0,0)的畫布變得可見或如此(任何)相關。你是否也嘗試了答案中的建議? – Marco13