key input Keylistener doesn't work for JOGL

classic Classic list List threaded Threaded
7 messages Options
Reply | Threaded
Open this post in threaded view
|

key input Keylistener doesn't work for JOGL

tragic_xxx
For some good reason i am using JOGL ....  Every other thing works well, including the static renderings, but the Input key binding keyListener doesn't work, I have got no clues why. I am hoping expert eyes inspection would be able to see whats wrong and also hope this code is small and clear enough for someone to be able to inspect it with ease
Many thanks

(I can't find code formatting tags, tried to make one but it isnt working. So apologies for the code, when I find code tags appear in menu , i will edit thread)

<code>public class Game extends JFrame implements GLEventListener, KeyListener  {
        private static final long serialVersionUID = 1L;
        final private int width = 800;
        final private int height = 600;
        int  right=-100, bottom=-100, top=100, left=100,       numOfUnits;
         GLU glu= new GLU();
     List<CreateObjVertices> dataArray;
     static Frame frame = new Frame();

        public Game(  int units,  List<CreateObjVertices> vertXYZ  ) {
                super("Minimal OpenGL");
                Globals.camera = new Point3D(0.0f, 1.4f, 0.0f);
                Globals.view = new Point3D(0.0f,  -1.0f, -3.0f);
                GLProfile profile = GLProfile.get(GLProfile.GL2);
                GLCapabilities capabilities = new GLCapabilities(profile);
                GLCanvas canvas = new GLCanvas(capabilities);
                //-------------------------------  
                //-------------------------------
                canvas.addGLEventListener(this);
                this.addKeyListener(this);    
            this.setFocusable(true);  // To receive key event
            this.requestFocus();

                this.setName("Minimal OpenGL");
                this.getContentPane().add(canvas);
                this.setSize(width, height);
                this.setLocationRelativeTo(null);
                this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                this.setVisible(true);
                this.setResizable(false);
                dataArray = vertXYZ;
                numOfUnits  =  units;
                canvas.requestFocusInWindow();
        }
       
        public void play() {
        }
       
    @Override
    public void display(GLAutoDrawable drawable) {
    GL2 gl = drawable.getGL().getGL2();
                 gl.glClear(GL2.GL_COLOR_BUFFER_BIT | GL2.GL_DEPTH_BUFFER_BIT);
       
                 gl.glMatrixMode(GL2.GL_MODELVIEW);            
                 gl.glLoadIdentity();      
                 glu.gluLookAt( Globals.camera.x, Globals.camera.y, Globals.camera.z,     Globals.view.x, Globals.view.y, Globals.view.z,    0.0f, 1.0f, 0.0f);
                 gl.glTranslatef(0.0f, 0.0f, -3.0f);
                 
         gl.glBegin(GL.GL_LINE_LOOP);
//==============        Note: I have edited this draw for clarity and it draws to my satisfaction, the key binding is the only problem in the code
         CreateObjVertices vertices;
         
             for( int t=0; t<numOfUnits; t++ ){

                   if( (t >= 0) ){
                vertices = dataArray.get( t );
                    gl.glColor3f(1, 0, 1);  

                                if( vertices.objectArrayLength > 0 ){    
                                        for(int k=0, s=0; k<vertices.objectArrayLength; k++, s=s+3){  
                                           
                                           gl.glVertex3f( vertices.objectVertexArray[k].x*1,   vertices.objectVertexArray[k].y*1,  vertices.objectVertexArray[k].z*1 );
               
                                   }
                                }
                        }  
             }
//=====
         gl.glEnd();
                 gl.glFlush();
    }

    @Override
    public void dispose(GLAutoDrawable drawable) {
   
    }

    @Override
    public void init(GLAutoDrawable drawable) {
    GL2 gl = drawable.getGL().getGL2();
    gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        gl.glClearDepthf(1.0f);            
        gl.glEnable(GL2.GL_DEPTH_TEST);  
        gl.glDepthFunc(GL2.GL_LEQUAL);  
        gl.glHint(GL2.GL_PERSPECTIVE_CORRECTION_HINT, GL2.GL_NICEST);  
        gl.glShadeModel(GL2.GL_SMOOTH);        
            gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
        }

    @Override
    public void reshape(GLAutoDrawable drawable, int x, int y, int width,  int height) {
    GL2 gl = drawable.getGL().getGL2();
                if (height == 0) height = 1;  
                float aspect = (float)width / height;
                gl.glViewport(0, 0, width, height);
                   
                gl.glMatrixMode(GL2.GL_PROJECTION);
                gl.glLoadIdentity();                
                glu.gluPerspective( 45, aspect, 0.1f, 100.0f);
    }

 
        @Override
        public void keyPressed(KeyEvent e) {
               
                if( e.getKeyChar() == 'x'){
                        System.out.println(" xxxx ");
                }
                if (e.getKeyChar() == KeyEvent.VK_LEFT) {
                        System.out.println(" LEFT ");
                }
                if (e.getKeyChar() == KeyEvent.VK_D) {
                        System.out.println(" DDDD ");
                }
                System.out.println(" LEFT ");
        }

        @Override
        public void keyReleased(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        System.out.println(" LEFT ");
                }
                System.out.println(" LEFT ");
        }

        @Override
        public void keyTyped(KeyEvent e) {
                if( e.getKeyCode() == 'x'){
                        System.out.println(" xxxx ");
                }
                if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                        System.out.println(" LEFT ");
                }
                if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                        System.out.println(" RIGHT ");
                }
                if (e.getKeyCode() == KeyEvent.VK_UP) {
                        System.out.println(" UP ");
                }
                if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                        System.out.println(" DOWN ");
                }
                System.out.println(" LEFT ");
        }    
}
</code>
Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

gouessej
Administrator
Hi

If the GLCanvas receives the key events, the key listener will have to be added to it instead of the JFrame, it's a basic Swing problem, it's not a JOGL problem. You could have the same kind of problem in a 2D game using only AWT, you have to put the key listener into the right component.

By the way, replace new GLU() by GLU.createGLU(GL) in order to use a more capable instance of GLU. glFlush is probably useless here.

Good luck.
Julien Gouesse | Personal blog | Website
Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

tragic_xxx
gouessej wrote
Hi

If the GLCanvas receives the key events, the key listener will have to be added to it instead of the JFrame, it's a basic Swing problem, it's not a JOGL problem. You could have the same kind of problem in a 2D game using only AWT, you have to put the key listener into the right component.

By the way, replace new GLU() by GLU.createGLU(GL) in order to use a more capable instance of GLU. glFlush is probably useless here.

Good luck.
Thank you for reply.  Can you elaborate further, I am rather new to these particular APIs.
How do I add the KeyListener to JFrame correctly (in this context)?
I tried to use GLU.createGLU(GL) instead of GLU(), but I must have written the wrongly because I had errors. So  how do I replace GLU() correctly?
Is it possible that you write the corrections over the original code and paste it in a reply? I will learn better that way.

Many thanks in advance

Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

jmaasing
tragic_xxx wrote
gouessej wrote
If the GLCanvas receives the key events, the key listener will have to be added to it instead of the JFrame, it's a basic Swing problem, it's not a JOGL problem.
How do I add the KeyListener to JFrame correctly (in this context)?
Swing works that way, one component will have the keyboard focus and only that component will get key events. So _IF_ the canvas has keyboard focus the listener must be added to the canvas.

https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

tragic_xxx
This post was updated on .
jmaasing wrote
tragic_xxx wrote
gouessej wrote
If the GLCanvas receives the key events, the key listener will have to be added to it instead of the JFrame, it's a basic Swing problem, it's not a JOGL problem.
How do I add the KeyListener to JFrame correctly (in this context)?
Swing works that way,...
https://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
I am a noob with this, I stated so and asked some questions, but you didn't read everything:::

"Thank you for reply.  Can you elaborate further, I am rather new to these particular APIs. 
How do I add the KeyListener to JFrame correctly (in this context)?
I tried to use GLU.createGLU(GL) instead of GLU(), but I must have written the wrongly because I had errors. So  how do I replace GLU() correctly?
Is it possible that you write the corrections over the original code and paste it in a reply? I will learn better that way.

Many thanks in advance
"

... I mean for newbies like me, reading only the theory often adds to the complexity and mystery of the issue, if not accompanied by a slight code snippet (in this case code correction).  Very honestly I am still lost as I got errors from my attempts to correct it

Is it possible that you write the corrections over the original code and paste it in a reply? As a newbie, I will learn better that way.

With regards and many thanks, all help appreciated
Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

gouessej
Administrator
In reply to this post by tragic_xxx
Maybe you should have looked at the simple examples in the wiki.

Replace "this.addKeyListener(this);" by "canvas.addKeyListener(this);".

You can create the GLU instance in the method GLEventListener.init(GLAutoDrawable):
    @Override
    public void init(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        glu = GLU.createGLU(gl);

I disagree with your answer to jmaasing. You must understand the concepts before applying them, otherwise you will just tinker some source code that you don't really understand. I simply advised you to add the key listener to the canvas rather than to the frame; if you don't succeed in understanding that it means that you have to modify just a single line of code to achieve this, it means that you don't even understand the source code you originally posted. We didn't speak to you only about the theory, we explained to you how to fix your code and why it works. Moreover, the Oracle tutorials are very well written, they explain the concepts and they contain numerous examples (including full source code most of the time), it's not just about theory. I'm sure that if you try to learn too much things too fast, you'll fail. There are no shortcomings, neither in Swing nor in computer graphics in general.

In my humble opinion, giving you the fixed source code without being sure that you understand both the original one and the fixed one instead of giving you the fixes with the necessary explanations is a bad solution and leads to spoon-feeding. We weren't born experts, we became experts, keep it in mind.
Julien Gouesse | Personal blog | Website
Reply | Threaded
Open this post in threaded view
|

Re: key input Keylistener doesn't work for JOGL

tragic_xxx
This post was updated on .
gouessej wrote
Maybe you should have looked at the simple examples in the wiki.

Replace "this.addKeyListener(this);" by "canvas.addKeyListener(this);".

You can create the GLU instance in the method GLEventListener.init(GLAutoDrawable):
    @Override
    public void init(GLAutoDrawable drawable) {
        GL2 gl = drawable.getGL().getGL2();
        glu = GLU.createGLU(gl);

I disagree with your answer to jmaasing. You must understand the concepts before applying them, otherwise you will just tinker some source code that you don't really understand. I simply advised you to add the key listener to the canvas rather than to the frame; if you don't succeed in understanding that it means that you have to modify just a single line of code to achieve this, it means that you don't even understand the source code you originally posted. We didn't speak to you only about the theory, we explained to you how to fix your code and why it works. Moreover, the Oracle tutorials are very well written, they explain the concepts and they contain numerous examples (including full source code most of the time), it's not just about theory. I'm sure that if you try to learn too much things too fast, you'll fail. There are no shortcomings, neither in Swing nor in computer graphics in general.

In my humble opinion, giving you the fixed source code without being sure that you understand both the original one and the fixed one instead of giving you the fixes with the necessary explanations is a bad solution and leads to spoon-feeding. We weren't born experts, we became experts, keep it in mind.
MANY THANKS Julien!
I didn't even know you meant just one line modification, actually I had to change a few more lines to get it working.
I don't disagree at all, what i'm just saying is for newbies the two go hand in hand otherwise terminologies become like abstracts. But once concepts are consolidated then i can understand terminologies without snippets

On the other hand I may be guilty of being very impatient to spend a lot time on the detail theory of how swing combines with Java OpenGL due to the fact that I'm actually working on a large project and this is just a very small part of it. Its actually an Android project and I'm porting the renderer to desktop so I can carry visual debugging better. Such debugging on Android device is nightmare at the moment and emulator is useless in this case

I have taken your advice onboard, Many Thanks