scala - glClearColor 仅显示黑屏
问题描述
我很难理解为什么我用openGL做的窗口保持黑色。
我看不出我在代码中哪里出错了:
import com.jogamp.opengl.awt.GLCanvas
import com.jogamp.opengl.{GL, GLAutoDrawable, GLCapabilities, GLEventListener, GLProfile}
import javax.swing.{JFrame, WindowConstants}
class Game extends JFrame ("Just a window OMG.") with GLEventListener {
val profile: GLProfile = GLProfile.get(GLProfile.GL4)
val capabilities = new GLCapabilities(profile)
val canvas = new GLCanvas(capabilities)
this.setName("Just a window OMG.")
this.getContentPane.add(canvas)
this.setSize(800, 600)
this.setLocationRelativeTo(null)
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE)
this.setVisible(true)
this.setResizable(false)
canvas.requestFocusInWindow
def play(): Unit = {
}
override def display(drawable: GLAutoDrawable): Unit = {
val gl = drawable.getGL.getGL4
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
gl.glFlush()
}
override def dispose(drawable: GLAutoDrawable): Unit = {}
override def init(drawable: GLAutoDrawable): Unit = {
val gl = drawable.getGL.getGL4
gl.glClearColor(1f, 0f, 0f, 1.0f)
}
override def reshape(drawable: GLAutoDrawable, x: Int, y: Int, width: Int, height: Int): Unit = {}
}
object Main {
def main(args: Array[String]): Unit = {
val game = new Game()
game.play()
}
}
我还尝试将 glClear 放在 display 方法中,并将 glClearColor 放在 init 方法中。
编辑:我找到了。实际上从未调用过 display 和 init 方法。侦听器未附加到画布上,因此它从未收到任何事件。
问题是我错过了这条线
canvas.addGLEventListener(this)
就在画布初始化之后。(这条线)
val canvas = new GLCanvas(capabilities)
解决方案
(我正在回答我自己的问题)
所以实际上问题是从未调用过 display 和 init 方法。据我了解, GLEventListener 正在等待事件,那些会触发 init 和 display 方法的调用。
注意到 GLEventListener 的“东西”是画布,但我的画布和 GLEventListener 没有绑定。
为此,我添加了该行
canvas.addGLEventListener(this)
就在我初始化画布之后,我可以注意到调用的 init 和 display 方法。