package yc021;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.fixedfunc.GLMatrixFunc;
import javax.media.opengl.glu.GLU;
import javax.swing.SwingUtilities;
public class MTriangle implements GLEventListener {
private float rot = 0;
private GL2 gl;
private GLU glu;
@Override
public void init(final GLAutoDrawable drawable) {
gl = drawable.getGL().getGL2();
glu = new GLU();
gl.setSwapInterval(1);
gl.glEnable(GL.GL_DEPTH_TEST);
}
@Override
public void display(final GLAutoDrawable drawable) {
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glLoadIdentity();
gl.glRotatef(rot++, 0, 0, 1);
gl.glColor3f(1.0f, 0.0f, 0.0f);
gl.glBegin(GL.GL_TRIANGLES);
gl.glVertex3f(-1.0f, -1.0f, -5.0f);
gl.glVertex3f(+1.0f, -1.0f, -5.0f);
gl.glVertex3f(+0.0f, +1.0f, -5.0f);
gl.glEnd();
}
@Override
public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, int height) {
if (height <= 0)
height = 1;
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(45.0f, (float)width / (float)height, 1.0, 20.0);
gl.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
gl.glLoadIdentity();
}
@Override
public void dispose(final GLAutoDrawable arg0) {
}
public static void main(final String[] args) throws InterruptedException, InvocationTargetException {
SwingUtilities.invokeAndWait(new Runnable() {
private volatile boolean run = true;
@Override
public void run() {
final MTriangle triangle = new MTriangle();
final Frame frame = new Frame();
final GLCanvas canvas = new GLCanvas();
canvas.addGLEventListener(triangle);
frame.add(canvas);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
final Thread animator = new Thread(new Runnable() {
@Override
public void run() {
while (run) {
canvas.display();
Thread.yield();
}
}
});
animator.start();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(final WindowEvent e) {
run = false;
new Thread(new Runnable() {
@Override
public void run() {
try {
animator.join();
} catch (final InterruptedException e) {
Thread.currentThread().interrupt();
}
System.exit(0);
}
}).start();
}
});
}
});
}
}