我正在尝试使用NetBeans和Swing的一个非常简单的JOGL教程,似乎无论我如何安排我不断获得空指针异常的东西。这是我正在使用的代码(改编自教程):
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(null)断点在第189行的sun.awt.image.OffScreenImageSource中被线程AWT-EventQueue-0命中。
我尝试了几种不同的JOGL教程,当我将画布添加到表单时,所有这些教程都会抛出此异常。我找不到OffScreenImageSource的代码,但是当我单步执行时,它会在Container.java中的第1119行死掉。代码是:
invalidateIfValid();
if (peer != null) {
comp.addNotify(); // <---- Dies right here
}
有没有人对可能导致这种情况的原因有任何想法?
答案 0 :(得分:1)
您的问题是您没有给Swing足够的时间来使用OS GDI正确初始化组件:只要您创建OpenGLTest()实例,就会调用doMain()。给Swing一些呼吸它应该有用。
public static void main(String args[]) {
OpenGLTest test;
java.awt.EventQueue.invokeLater(() -> {
test = new OpenGLTest()
});
java.awt.EventQueue.invokeLater(() -> {
test.doMain();
});
}
仅供参考,我没有验证语法。