tags:

views:

49

answers:

1

Hi all,

I am started to deal with opengl. My application is written in Java using SWT as windowing system.

Using http://lwjgl.org/ and SWT, I am able to use opengl in my SWT canvas. I wrote the following simple opengl code in my canvas paint listener:

// clear to background color
GL11.glClearColor(.3f, .5f, .8f, 1.0f);
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);

// draw rectangle
GL11.glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
GL11.glMatrixMode(GL11.GL_PROJECTION);
GL11.glLoadIdentity();
GL11.glBegin(GL11.GL_POLYGON);
GL11.glVertex3f(0.1f, 0.1f, 0.0f);
GL11.glVertex3f(0.1f, 0.9f, 0.0f);
GL11.glVertex3f(0.9f, 0.9f, 0.0f);
GL11.glVertex3f(0.9f, 0.1f, 0.0f);
GL11.glEnd();
GL11.glFlush();

I want know to add a resize listener on my canvas in order to always have my rectangle in the center of the window. How should I do that ?

Thanks in advance, Manu

+1  A: 

You need to manually set your viewport size by calling glViewport() every time canvas size changes. After that your screen will have dimensions specified by glOrtho().

Also, your matrices are a mess. Projection matrix is used for projection only and modelview for other transformations (rotation, scaling, moving, etc.).

// Viewport (needs to be done on canvas resize only)
GL11.glViewport(0.0, 0.0,                   // Set viewport size
                canvas.getBounds().width,
                canvas.getBounds().height);

// Projection (only needs to be set once in most cases)
GL11.glMatrixMode(GL11.GL_PROJECTION);        // Select projection matrix
GL11.glLoadIdentity();                        // Clear it
GL11.glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);  // Set your projection

// model/view transforms
GL11.glMatrixMode(GL11.GL_MODELVIEW);  // Select modelview matrix
GL11.glLoadIdentity();                 // Clear it

// Draw (shortcut)
GL11.glRectf(0.1f, 0.1f, 0.9f, 0.9f);
Ivan Baldin