Last active
June 2, 2019 16:27
-
-
Save hageldave/f22d6c3ef5120a7c711553426c72abcd to your computer and use it in GitHub Desktop.
AWTGLCanvas draw on demand
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.awt.Dimension; | |
import java.awt.Graphics; | |
import java.awt.event.ComponentAdapter; | |
import javax.swing.JFrame; | |
import javax.swing.SwingUtilities; | |
import org.lwjgl.opengl.GL; | |
import org.lwjgl.opengl.GL11; | |
import org.lwjgl.opengl.awt.AWTGLCanvas; | |
public class DrawOnDemand { | |
public static void main(String[] args) { | |
AWTGLCanvas canvas = new AWTGLCanvas() { | |
@Override | |
public void paintGL() { | |
int w = getWidth(); | |
int h = getHeight(); | |
if(w==0 || h == 0){ | |
return; | |
} | |
float aspect = (float) w / h; | |
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); | |
GL11.glViewport(0, 0, w, h); | |
GL11.glBegin(GL11.GL_QUADS); | |
GL11.glColor3f(0.4f, 0.6f, 0.8f); | |
GL11.glVertex2f(-0.75f / aspect, 0.0f); | |
GL11.glVertex2f(0, -0.75f); | |
GL11.glVertex2f(+0.75f / aspect, 0); | |
GL11.glVertex2f(0, +0.75f); | |
GL11.glEnd(); | |
swapBuffers(); | |
} | |
@Override | |
public void initGL() { | |
GL.createCapabilities(); | |
} | |
@Override | |
public void repaint() { | |
if(SwingUtilities.isEventDispatchThread()){ | |
render(); | |
} else { | |
SwingUtilities.invokeLater(()->render()); | |
} | |
} | |
/** | |
* NOOP - this canvas is painted using OpenGL through the {@link #render()} method. | |
*/ | |
@Override | |
public final void paint(Graphics g) { | |
// don't modify the graphics object | |
} | |
/** | |
* NOOP - this canvas is painted using OpenGL through the {@link #render()} method. | |
*/ | |
@Override | |
public final void paintAll(Graphics g) { | |
// don't modify the graphics object | |
} | |
/** | |
* NOOP - this canvas is painted using OpenGL through the {@link #render()} method. | |
*/ | |
@Override | |
public final void update(Graphics g) { | |
// don't modify the graphics object | |
} | |
}; | |
JFrame frame = new JFrame(); | |
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); | |
frame.getContentPane().add(canvas); | |
canvas.setPreferredSize(new Dimension(200, 200)); | |
canvas.addComponentListener(new ComponentAdapter() { | |
public void componentResized(java.awt.event.ComponentEvent e) { | |
canvas.repaint(); | |
}; | |
}); | |
SwingUtilities.invokeLater(()->{ | |
frame.pack(); | |
frame.setVisible(true); | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment