java addKeyListener(this)在JOGL中抛出错误

yrwegjxp  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(103)

我想旋转立方体,如果我按下左箭头键和右箭头键分别移动水平轴和垂直轴。因此,我在这个程序中使用了keyListener接口。当示例化keyListener时,它抛出错误,特此附上我的代码供您参考。

import java.io.*;
import java.lang.Math;
import java.nio.*;
import javax.swing.*;
import static com.jogamp.opengl.GL4.*;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.util.texture.*;
import com.jogamp.common.nio.Buffers;
import com.jogamp.newt.event.KeyListener;

import org.joml.*;
import java.awt.event.KeyEvent;

public class Code extends JFrame implements GLEventListener,KeyListener
{   private GLCanvas myCanvas;
    
    private int renderingProgram;
    private int vao[] = new int[1];
    private int vbo[] = new int[3];
    private float cameraX, cameraY, cameraZ;
    private float objLocX, objLocY, objLocZ;
    
    // allocate variables for display() function
    private FloatBuffer vals = Buffers.newDirectFloatBuffer(16);
    private Matrix4f pMat = new Matrix4f();  // perspective matrix
    private Matrix4f vMat = new Matrix4f();  // view matrix
    private Matrix4f mMat = new Matrix4f();  // model matrix
    private Matrix4f mvMat = new Matrix4f(); // model-view matrix
    private int mvLoc, pLoc;
    private float aspect;
    
    private int shuttleTexture;
    private int rotateX = 0,rotateY = 0;
    
    private int numObjVertices;
    private ImportedModel myModel;
    

    public Code()
    {   setTitle("Chapter6 - program3");
        setSize(600, 600);
        myCanvas = new GLCanvas();
        myCanvas.addKeyListener(this); //this line throws an error.
        myCanvas.addGLEventListener(this);
        
        this.add(myCanvas);
        myCanvas.setFocusable(true);
        this.setVisible(true);
    }

    public void display(GLAutoDrawable drawable)
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
        gl.glClear(GL_COLOR_BUFFER_BIT);
        gl.glClear(GL_DEPTH_BUFFER_BIT);

        gl.glUseProgram(renderingProgram);

        int mvLoc = gl.glGetUniformLocation(renderingProgram, "mv_matrix");
        int pLoc = gl.glGetUniformLocation(renderingProgram, "p_matrix");

        vMat.identity().setTranslation(-cameraX,-cameraY,-cameraZ);

        mMat.identity();
        mMat.translate(objLocX, objLocY, objLocZ);

        mMat.rotateX((float)Math.toRadians(20.0f));
        mMat.rotateY((float)Math.toRadians(130.0f));
        mMat.rotateZ((float)Math.toRadians(5.0f));

        mvMat.identity();
        mvMat.mul(vMat);
        mvMat.mul(mMat);

        gl.glUniformMatrix4fv(mvLoc, 1, false, mvMat.get(vals));
        gl.glUniformMatrix4fv(pLoc, 1, false, pMat.get(vals));

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
        gl.glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
        gl.glEnableVertexAttribArray(0);

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
        gl.glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0);
        gl.glEnableVertexAttribArray(1);

        gl.glActiveTexture(GL_TEXTURE0);
        gl.glBindTexture(GL_TEXTURE_2D, shuttleTexture);

        gl.glEnable(GL_DEPTH_TEST);
        gl.glDepthFunc(GL_LEQUAL);
        gl.glDrawArrays(GL_TRIANGLES, 0, myModel.getNumVertices());
    }

    public void init(GLAutoDrawable drawable)
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
    
        myModel = new ImportedModel("cube1.obj");
        renderingProgram = Utils.createShaderProgram("src/code/vertShader.glsl", "src/code/fragShader.glsl");

        float aspect = (float) myCanvas.getWidth() / (float) myCanvas.getHeight();
        pMat.identity().setPerspective((float) Math.toRadians(60.0f), aspect, 0.1f, 1000.0f);

        setupVertices();
        cameraX = 0.0f; cameraY = 0.0f; cameraZ = 3.0f;
        objLocX = 0.0f; objLocY = 0.0f; objLocZ = 0.0f;

        shuttleTexture = Utils.loadTexture("Material5.jpg");
    }

    private void setupVertices()
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
    
        numObjVertices = myModel.getNumVertices();
        Vector3f[] vertices = myModel.getVertices();
        Vector2f[] texCoords = myModel.getTexCoords();
        Vector3f[] normals = myModel.getNormals();
        
        float[] pvalues = new float[numObjVertices*3];
        float[] tvalues = new float[numObjVertices*2];
        float[] nvalues = new float[numObjVertices*3];
        
        for (int i=0; i<numObjVertices; i++)
        {   pvalues[i*3]   = (float) (vertices[i]).x() + rotateX;
            pvalues[i*3+1] = (float) (vertices[i]).y() + rotateY;
            pvalues[i*3+2] = (float) (vertices[i]).z();
            tvalues[i*2]   = (float) (texCoords[i]).x();
            tvalues[i*2+1] = (float) (texCoords[i]).y();
            nvalues[i*3]   = (float) (normals[i]).x();
            nvalues[i*3+1] = (float) (normals[i]).y();
            nvalues[i*3+2] = (float) (normals[i]).z();
        }
        
        gl.glGenVertexArrays(vao.length, vao, 0);
        gl.glBindVertexArray(vao[0]);
        gl.glGenBuffers(vbo.length, vbo, 0);
        
        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
        FloatBuffer vertBuf = Buffers.newDirectFloatBuffer(pvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, vertBuf.limit()*4, vertBuf, GL_STATIC_DRAW);

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
        FloatBuffer texBuf = Buffers.newDirectFloatBuffer(tvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, texBuf.limit()*4, texBuf, GL_STATIC_DRAW);

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
        FloatBuffer norBuf = Buffers.newDirectFloatBuffer(nvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, norBuf.limit()*4,norBuf, GL_STATIC_DRAW);
    }
    
    

    public void keyTyped(KeyEvent e) {}
    

    public static void main(String[] args) { 
        new Code();}

    public void dispose(GLAutoDrawable drawable) {}
    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)
    {   float aspect = (float) myCanvas.getWidth() / (float) myCanvas.getHeight();
        pMat.identity().setPerspective((float) Math.toRadians(60.0f), aspect, 0.1f, 1000.0f);
    }

    public void keyPressed(com.jogamp.newt.event.KeyEvent arg0) {
        // TODO Auto-generated method stub
        int key = arg0.getKeyCode();
        System.out.println(arg0.getKeyCode());
        if ( key == KeyEvent.VK_LEFT )
        {
            rotateX +=2;
            System.out.println("Left arrow is pressed");
        }
        else if ( key == KeyEvent.VK_RIGHT )
            rotateY += 2;
        else if ( key == KeyEvent.VK_DOWN)
            rotateX += 2;
        else if ( key == KeyEvent.VK_UP )
            rotateX -= 2;
        else if ( key == KeyEvent.VK_HOME )
            rotateX = rotateY = 0;
        
    }

    public void keyReleased(com.jogamp.newt.event.KeyEvent arg0) {}
}

输出

The method addKeyListener(KeyListener) in the type Component is not applicable for the arguments (Code)

为什么我无法添加添加keylistener在opengl java?

b09cbbtk

b09cbbtk1#

我修改并添加了这些行
int getMaxProgrammableCore(true);
int n = new int n();
MyCanvas = new GLCanvas(c);
现在我可以在我的程序中做键监听器接口了。

代码:

import java.io.*;
import java.lang.Math;
import java.nio.*;
import javax.swing.*;
import static com.jogamp.opengl.GL4.*;
import com.jogamp.opengl.util.*;
import com.jogamp.opengl.*;
import com.jogamp.opengl.awt.GLCanvas;
import com.jogamp.opengl.util.texture.*;
import com.jogamp.common.nio.Buffers;
import org.joml.*;
import com.jogamp.opengl.GLContext;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class Code extends JFrame implements GLEventListener,KeyListener
{   private GLCanvas myCanvas;
    private int renderingProgram;
   private double startTime = 0.0;
    private double elapsedTime;
    private int vao[] = new int[1];
    private int vbo[] = new int[3];
    private float cameraX, cameraY, cameraZ;
    private float objLocX, objLocY, objLocZ;
    
    // allocate variables for display() function
    private FloatBuffer vals = Buffers.newDirectFloatBuffer(16);
    private Matrix4f pMat = new Matrix4f();  // perspective matrix
    private Matrix4f vMat = new Matrix4f();  // view matrix
    private Matrix4f mMat = new Matrix4f();  // model matrix
    private Matrix4f mvMat = new Matrix4f(); // model-view matrix
    private int mvLoc, pLoc;
    private float aspect;
    
    private int shuttleTexture;
    
    private int numObjVertices;
    private ImportedModel myModel;
   
   private double tf;
   int i = 0;
   double incX;
   double incY;
   int setx = 2;
   
   boolean toggle = false;
   boolean texToggle = false;

    public Code()
    {   setTitle("Chapter6 - program3");
        setSize(600, 600);
      GLProfile g = GLProfile.getMaxProgrammableCore(true);

      GLCapabilities c = new GLCapabilities(g);
      
      myCanvas = new GLCanvas(c);

        myCanvas.addGLEventListener(this);
      myCanvas.addKeyListener(this);
      myCanvas.setFocusable(true);
        this.add(myCanvas);
        this.setVisible(true);
      Animator animator = new Animator(myCanvas);
        animator.start();
    }

    public void display(GLAutoDrawable drawable)
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
        gl.glClear(GL_COLOR_BUFFER_BIT);
        gl.glClear(GL_DEPTH_BUFFER_BIT);
      elapsedTime = System.currentTimeMillis() - startTime;
      
        tf = elapsedTime/1000.0; 
      
      if(texToggle){
           shuttleTexture = Utils.loadTexture("Material5.jpg");
      }
         else{
           shuttleTexture = Utils.loadTexture("dhoni.jpg");   
      }

        gl.glUseProgram(renderingProgram);

        int mvLoc = gl.glGetUniformLocation(renderingProgram, "mv_matrix");
        int pLoc = gl.glGetUniformLocation(renderingProgram, "p_matrix");

        vMat.identity().setTranslation(-cameraX,-cameraY,-cameraZ);
      
      for(int yUp = -1; yUp<=1; yUp += 1){
         for(int i = 0; i < 9; i++){
         
   
               mMat.identity();
               mMat.rotateX((float)Math.toRadians(incX));
               mMat.rotateY((float)Math.toRadians(incY));
               
               if(i==0){
               
                  mMat.translate(0*setx,yUp*setx,0*setx);
               }
               else if(i == 1){
                  mMat.translate(-1*setx,yUp*setx,0*setx);
               }
               
                else if(i == 2){
                  mMat.translate(1*setx,yUp*setx,0*setx);
               }
   
                else if(i == 3){
                  mMat.translate(0*setx,yUp*setx,-1*setx);
               }
                else if(i == 4){
                  mMat.translate(0*setx,yUp*setx,1*setx);
               }
                else if(i == 5){
                  mMat.translate(1*setx,yUp*setx,-1*setx);
               }
               else if(i == 6){
                  mMat.translate(1*setx,yUp*setx,1*setx);
               }
               
               else if(i == 7){
                  mMat.translate(-1*setx,yUp*setx,-1*setx);
               }
                else if(i == 8){
                  mMat.translate(-1*setx,yUp*setx,1*setx);
               }
   

            mMat.rotateX((float)Math.toRadians(180.f));
            mMat.rotateY((float)Math.toRadians(180.f));
            mMat.rotateZ((float)Math.toRadians(90.0f));

      
            mvMat.identity();
            mvMat.mul(vMat);
            mvMat.mul(mMat);
    
            gl.glUniformMatrix4fv(mvLoc, 1, false, mvMat.get(vals));
            gl.glUniformMatrix4fv(pLoc, 1, false, pMat.get(vals));
      
            gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
            gl.glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
            gl.glEnableVertexAttribArray(0);
      
            gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
            gl.glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0);
            gl.glEnableVertexAttribArray(1);
      
            gl.glActiveTexture(GL_TEXTURE0);
            gl.glBindTexture(GL_TEXTURE_2D, shuttleTexture);
            
            if (toggle){
               gl.glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
            }
            else{
               gl.glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
            } 
            
            gl.glEnable(GL_DEPTH_TEST);
            gl.glDepthFunc(GL_LEQUAL);
            gl.glDrawArrays(GL_TRIANGLES, 0, myModel.getNumVertices());
               
      }
    }
   
   
   }

    public void init(GLAutoDrawable drawable)
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
        startTime = System.currentTimeMillis();
        myModel = new ImportedModel("cube1.obj");
        renderingProgram = Utils.createShaderProgram("code/vertShader.glsl", "code/fragShader.glsl");

        float aspect = (float) myCanvas.getWidth() / (float) myCanvas.getHeight();
        pMat.identity().setPerspective((float) Math.toRadians(60.0f), aspect, 0.1f, 1000.0f);

        setupVertices();
      cameraX = 0.0f; cameraY = 0.0f; cameraZ = 25.0f;
        objLocX = 100.0f; objLocY = 100.0f; objLocZ = 100.0f;

      if(texToggle){
           shuttleTexture = Utils.loadTexture("Material5.jpg");
      }
      else{
           shuttleTexture = Utils.loadTexture("dhoni.jpg");

      }

      
    }

    private void setupVertices()
    {   GL4 gl = (GL4) GLContext.getCurrentGL();
    
        numObjVertices = myModel.getNumVertices();
        Vector3f[] vertices = myModel.getVertices();
        Vector2f[] texCoords = myModel.getTexCoords();
        Vector3f[] normals = myModel.getNormals();
        
        float[] pvalues = new float[numObjVertices*3];
        float[] tvalues = new float[numObjVertices*2];
        float[] nvalues = new float[numObjVertices*3];
        
        for (int i=0; i<numObjVertices; i++)
        {   pvalues[i*3]   = (float) (vertices[i]).x();
            pvalues[i*3+1] = (float) (vertices[i]).y();
            pvalues[i*3+2] = (float) (vertices[i]).z();
            tvalues[i*2]   = (float) (texCoords[i]).x();
            tvalues[i*2+1] = (float) (texCoords[i]).y();
            nvalues[i*3]   = (float) (normals[i]).x();
            nvalues[i*3+1] = (float) (normals[i]).y();
            nvalues[i*3+2] = (float) (normals[i]).z();
        }
        
        gl.glGenVertexArrays(vao.length, vao, 0);
        gl.glBindVertexArray(vao[0]);
        gl.glGenBuffers(vbo.length, vbo, 0);
        
        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
        FloatBuffer vertBuf = Buffers.newDirectFloatBuffer(pvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, vertBuf.limit()*4, vertBuf, GL_STATIC_DRAW);

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]);
        FloatBuffer texBuf = Buffers.newDirectFloatBuffer(tvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, texBuf.limit()*4, texBuf, GL_STATIC_DRAW);

        gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[2]);
        FloatBuffer norBuf = Buffers.newDirectFloatBuffer(nvalues);
        gl.glBufferData(GL_ARRAY_BUFFER, norBuf.limit()*4,norBuf, GL_STATIC_DRAW);
    }

   public void keyPressed(KeyEvent e) {
        System.out.println("keyPressed");
        if(e.getKeyCode()== KeyEvent.VK_RIGHT)
            incY  += 20.0f;
               
        else if(e.getKeyCode()== KeyEvent.VK_LEFT)
            incY  -= 20.0f;
        else if(e.getKeyCode()== KeyEvent.VK_UP)
            incX  += 20.0f;
            
        else if(e.getKeyCode()== KeyEvent.VK_DOWN)
            incX  -= 20.0f;
        else if(e.getKeyCode()== KeyEvent.VK_E)
            setx  += 3;
        else if(e.getKeyCode()== KeyEvent.VK_C)
            setx  -= 1;
        else if(e.getKeyCode()== KeyEvent.VK_L)
            toggle = !toggle;
        else if(e.getKeyCode()== KeyEvent.VK_X)
            cameraZ -= 2.0f;
        else if(e.getKeyCode()== KeyEvent.VK_Z)
            cameraZ += 4.0f;
        else if(e.getKeyCode()== KeyEvent.VK_T ){
           texToggle = !texToggle;

        }

    }

    public void keyReleased(KeyEvent e) {
    
      
    
       System.out.println("keyReleased");
      
    }
    public void keyTyped(KeyEvent e) {
        System.out.println("keyTyped");
    }

    public static void main(String[] args) { new Code(); }
    public void dispose(GLAutoDrawable drawable) {}
    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height)
    {   float aspect = (float) myCanvas.getWidth() / (float) myCanvas.getHeight();
        pMat.identity().setPerspective((float) Math.toRadians(60.0f), aspect, 0.1f, 1000.0f);
    }
}

相关问题