Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: MouseListener doesn't work and It blocks KeyListener

  1. #1
    Junior Member
    Join Date
    Apr 2019
    Posts
    0
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default MouseListener doesn't work and It blocks KeyListener

    Hi all, i am having problems handling MouseListener and KeyListener.

    I will show you the main class that create a JFrame and draw some geometric things in 2D. I have implemented Key inputs to change the things drawn and it works well. Now I want to implement Mouse inputs to add more functionality but it doesn`t work and it blocks my keyListener. I mean, if I click on the JFrame, nothing happens and then I cant use keys.


     
    public class Test extends Frame implements GLEventListener, MouseListener,KeyListener{
     
        static int A = 0;
        static int B = 1;
        static int C = 2;
        static int D = 3;
        static int HEIGHT = 800;
        static int WIDTH = 800;
        static int POINT_CLOUD_VERT = 30;
        static GL gl; // interface to OpenGL
        static GLCanvas canvas; // drawable in a frame
        static GLCapabilities capabilities;
        static boolean visualizeAxis = true;
        static int exercise = A;
        static Animator animator;
     
        // Geometric data in memory
        // Exercise A 
        Point p1;
        DrawPoint dp1;
     
        PointCloud pc;
        DrawPointCloud dc;
     
        SegmentLine s1;
        DrawSegment ds1;
     
        RayLine r1;
        DrawRay dr1;
     
        Line l1;
        DrawLine dl1;
     
        Vector v1;
        DrawVector dv1;
     
        Polygon pol;
        DrawPolygon dpol;
     
        Circle cir;
        DrawCircle dcir; 
     
        //Exercise B
        Point p2;
        DrawPoint dp2;
     
        SegmentLine s2;
        DrawSegment ds2;
     
        Line l2;
        DrawLine dl2;
     
        RayLine r2;
        DrawRay dr2;
     
        Circle cir2;
        DrawCircle dcir2;
     
        Circle cir3;
        DrawCircle dcir3;
     
        Circle cir4;
        DrawCircle dcir4;
     
        TDelaunay td;
        DrawTDelaunay dtd;
     
        TDelaunay td2;
        DrawTDelaunay dtd2;
     
        PointCloud pcTD;
        DrawPointCloud dpcTD;
        PointCloud pcTD2;
        DrawPointCloud dpcTD2;
        PointCloud pcTD2P;
     
        List<Point> puntosNube = new ArrayList<Point>(50);
     
        public Test(String title) {
            super(title);
     
            // 1. specify a drawable: canvas
            capabilities = new GLCapabilities();
            capabilities.setDoubleBuffered(false);
            canvas = new GLCanvas();
     
            // 2. listen to the events related to canvas: reshape
            canvas.addGLEventListener(this);
     
            // 3. add the canvas to fill the Frame container
            add(canvas, BorderLayout.CENTER);
     
            // 4. interface to OpenGL functions
            gl = canvas.getGL();
     
            addWindowListener(new WindowAdapter() {
     
                public void windowClosing(WindowEvent e) {
    //				animator.stop(); // stop animation
                    System.exit(0);
                }
            });
     
            addMouseListener(this);
            addKeyListener(this);
     
     
     
        }
     
        protected void initExerciseA() throws Exception {
            RandomGen random = RandomGen.getInst();
            pc = new PointCloud(POINT_CLOUD_VERT);
            //pc = new PointCloud("nube17.txt");
            pc.save("nube17.txt");
            dc = new DrawPointCloud(pc);
     
            //Draw a point
            p1 = new Point(4,3);
            dp1 = new DrawPoint(p1);
     
            //Segments with 2 random points
            s1 = new SegmentLine(pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT), pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT));
            ds1 = new DrawSegment(s1);
     
            //Ray with random points
            r1 = new RayLine(pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT), pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT));
            dr1 = new DrawRay(r1);
     
            //Liney with random points
            l1 = new Line(pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT), pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT));
            dl1 = new DrawLine(l1);
     
            // Polygon
     
            //Polygon poligono = new Polygon("./prueba.txt");
            //poligono.save("guardado.txt");
            ArrayList< Point> coord = new ArrayList< Point>();
            GeomMethods.get4Corners(coord, pc);
            Polygon pol = GeomMethods.create4Polygon(coord.get(0), coord.get(1), coord.get(2), coord.get(3));
            pol.save("polEsquinas.txt");
            encontrarConvexo(pol);
            pol.save("convexPol");
            dpol = new DrawPolygon(pol);
     
            //Circle located at the most central point
            Point center = pc.centralPoint();
            Point pr = pc.getPoint(random.nextUInt() % POINT_CLOUD_VERT);
            double radio = center.distance(pr);
            cir = new Circle(center, radio);
            dcir = new DrawCircle(cir);
        }
     
        protected void drawExerciseA() {
            dc.drawObjectC(gl, 1.0f,1.0f,0.0f);
            dp1.drawObjectC(gl, 0.3f, 0.0f, 0.8f);
            ds1.drawObjectC(gl, 0.5f, 0.2f, 0.3f);
            //ds1.drawObjectC(gl, 1.0f, 0.5f, 0.5f);
            dr1.drawObjectC(gl, 0.2f, 0.82f, 0.3f);
            dl1.drawObjectC(gl, 0.1f, 0.44f, 0.7f);
            dpol.drawObjectC(gl, 0.9f, 0.3f, 0.1f);
            //dc.drawObjectC(gl, 1.0f, 0.0f, 0.5f);
            dcir.drawObjectC(gl, 1.0f, 0.0f, 0.5f);
        }
     
     
        protected void initExerciseB() {
            ///XXXX
            l2 = new Line(new Point(-60,60), new Point(60,60));
            dl2 = new DrawLine(l2);
     
            r2 = new RayLine(new Point(-55,-10),new Point(25,30));
            dr2 = new DrawRay(r2);
     
     
            cir2 = new Circle(new Point(0,0),25.0f);
            dcir2 = new DrawCircle(cir2);
     
            cir3 = new Circle(new Point(0,-40),25);
            dcir3 = new DrawCircle(cir3);
     
            cir4 = new Circle(new Point(35,-40),10);
            dcir4 = new DrawCircle(cir4);
     
            s2 = new SegmentLine(new Point(25,40),new Point(25,-35));
            ds2 = new DrawSegment(s2);
     
            p2 = new Point(-40,40);
            dp2 = new DrawPoint(p2);
     
            System.out.println("La distancia entre el punto P("+p2.getX()+","+p2.getY()+") y la recta A es: "+l2.distPointLine(new Vector(p2)));
            System.out.println("La distancia entre el punto P("+p2.getX()+","+p2.getY()+") y el rayo B es: "+r2.distPointRay(new Vector(p2)));
            System.out.println("La distancia entre el punto P("+p2.getX()+","+p2.getY()+") y el circulo C es: "+p2.distance(cir2.getCenter()));
     
            Vector intersecta = new Vector();
            Vector intersecta2 = new Vector();
            if(l2.intersecta(r2, intersecta)){
                System.out.println("La recta A intersecta con el rayo B en el punto "+intersecta.getX()+","+intersecta.getY());
            }else{
                System.out.println("La recta A NO intersecta con el rayo B");
            }
     
            if(l2.intersecta(s2, intersecta)){
                System.out.println("La recta A intersecta con el segmento D en el punto "+intersecta.getX()+","+intersecta.getY());
            }else{
                System.out.println("La recta A NO intersecta con el segmento D");
            }
     
            if(r2.intersecta(s2, intersecta)){
                System.out.println("El rayo B intersecta con el segmento D en el punto "+intersecta.getX()+","+intersecta.getY());
            }else{
                System.out.println("El rayo B NO intersecta con el segmento D");
            }
     
            Circle.RelationCircleLine relacion = cir2.intersects(l2, intersecta, intersecta2);
            if(relacion==Circle.RelationCircleLine.INTERSECTS){
                System.out.println("El circulo C intersecta con la recta A en los puntos "+intersecta.getX()+","+intersecta.getY()+
                        " y "+intersecta2.getX()+","+intersecta2.getY());
            }
            if(relacion==Circle.RelationCircleLine.TANGENTS){
                System.out.println("El circulo C es tangente con la recta A en el punto "+intersecta.getX()+","+intersecta.getY());
            }
     
            if(relacion == Circle.RelationCircleLine.NO_INTERSECTS){
                System.out.println("El circulo C NO intersecta con la recta A");
            }
     
            relacion = cir2.intersects(r2, intersecta, intersecta2);
            if(relacion==Circle.RelationCircleLine.INTERSECTS){
                System.out.println("El circulo C intersecta con el rayo B en los puntos "+intersecta.getX()+","+intersecta.getY()+
                        " y "+intersecta2.getX()+","+intersecta2.getY());
            }
            if(relacion==Circle.RelationCircleLine.TANGENTS){
                System.out.println("El circulo C es tangente con el rayo B en el punto "+intersecta.getX()+","+intersecta.getY());
            }
     
            if(relacion == Circle.RelationCircleLine.NO_INTERSECTS){
                System.out.println("El circulo C NO intersecta con el rayo B");
            }
     
            relacion = cir2.intersects(s2, intersecta, intersecta2);
            if(relacion==Circle.RelationCircleLine.INTERSECTS){
                System.out.println("El circulo C intersecta con el segmento D en los puntos "+intersecta.getX()+","+intersecta.getY()+
                        " y "+intersecta2.getX()+","+intersecta2.getY());
            }
            if(relacion==Circle.RelationCircleLine.TANGENTS){
                System.out.println("El circulo C es tangente con el segmento D en el punto "+intersecta.getX()+","+intersecta.getY());
            }
     
            if(relacion == Circle.RelationCircleLine.NO_INTERSECTS){
                System.out.println("El circulo C NO intersecta con el segmento D");
     
            }
     
            System.out.println("Los circulos 1 y 2 son: "+ cir2.circleRelation(cir3));
            System.out.println("Los circulos 2 y 3 son: "+cir3.circleRelation(cir4));
     
        }
     
     
     
        protected void drawExerciseB() {
            //XXXXXX
            dp2.drawObjectC(gl, 0.3f, 0.0f, 0.8f);
            ds2.drawObjectC(gl, 0.5f, 0.2f, 0.3f);
            dr2.drawObjectC(gl, 0.2f, 0.82f, 0.3f);
            dl2.drawObjectC(gl, 0.1f, 0.44f, 0.7f);
            dcir2.drawObjectC(gl, 1.0f, 0.0f, 0.5f);
            dcir3.drawObjectC(gl, 1.0f, 0.0f, 0.5f);
            dcir4.drawObjectC(gl, 1.0f, 0.0f, 0.5f);
     
        }
     
        protected void initExerciseTDelanuay()
        {
            pcTD = new PointCloud(100);
            td = new TDelaunay(pcTD);
            dtd = new DrawTDelaunay(td);
            dpcTD = new DrawPointCloud(pcTD);
        }
     
        protected void initExerciseTDelanuay2()
        {
            pcTD2 = new PointCloud(50);
            pcTD2P = new PointCloud(pcTD2);
            dpcTD2 = new DrawPointCloud(pcTD2P);
            int pos1 = Math.abs(RandomGen.getInst().nextInt())%pcTD2.size();
            puntosNube.add(pcTD2.removePoint(pos1));
            int pos2 = Math.abs(RandomGen.getInst().nextInt())%pcTD2.size();
            puntosNube.add(pcTD2.removePoint(pos2));
            int pos3 = Math.abs(RandomGen.getInst().nextInt())%pcTD2.size();
            puntosNube.add(pcTD2.removePoint(pos3));
            Point p1 = puntosNube.remove(0);
            Point p2 = puntosNube.remove(0);
            Point p3 = puntosNube.remove(0);
            td2 = new TDelaunay(p1,p2,p3);
            dtd2 = new DrawTDelaunay(td2);
     
     
        }
     
        protected void drawTDelanuay()
        {
            dtd.drawObjectC(gl, 1.0f, 0.0f, 0.0f);
            dpcTD.drawObjectC(gl, 0.0f, 0.0f, 1.0f);
        }
     
        protected void drawTDelanuay2() throws InterruptedException
        {
     
            dpcTD2.drawObjectC(gl, 0.0f, 0.0f, 1.0f);
            dtd2.drawObjectC(gl, 1.0f, 0.0f, 0.0f);
            if (pcTD2.size() != 0)
            {
                int posRandom = Math.abs(RandomGen.getInst().nextInt()) % pcTD2.size();
                puntosNube.add(pcTD2.removePoint(posRandom));
                td2.addPoint(puntosNube.remove(0));
                Thread.sleep(1000);
            }
        }
     
     
        // called once for OpenGL initialization
     
        public void init(GLAutoDrawable drawable) {
     
            animator = new Animator(canvas);
            animator.start(); // start animator thread
            // display OpenGL and graphics system information
            System.out.println("INIT GL IS: " + gl.getClass().getName());
            System.err.println(drawable.getChosenGLCapabilities());
            System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR));
            System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER));
            System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION));
     
            RandomGen random = RandomGen.getInst();
            //random.setSeed(5308170449555L);
            System.err.println("SEED: " + random.getSeed());
     
            try {
     
                initExerciseA();
                initExerciseB();
                initExerciseTDelanuay();
                initExerciseTDelanuay2();
     
            } catch (Exception ex) {
                System.out.println("Error en el dibujado");
                ex.printStackTrace();
            }
     
        }
     
     
        public void reshape(GLAutoDrawable drawable, int x, int y, int width,
                int height) {
     
            Draw.WIDTH = WIDTH = width; // new width and height saved
            Draw.HEIGH = HEIGHT = height;
            //DEEP = deep;
            if (Draw.HEIGH < Draw.WIDTH) {
                Draw.WIDTH = Draw.HEIGH;
            }
            if (Draw.HEIGH > Draw.WIDTH) {
                Draw.HEIGH = Draw.WIDTH;
            }
            // 7. specify the drawing area (frame) coordinates
            gl.glMatrixMode(GL.GL_PROJECTION);
            gl.glLoadIdentity();
            gl.glOrtho(0, width, 0, height, -100, 100);
            gl.glMatrixMode(GL.GL_MODELVIEW);
            gl.glLoadIdentity();
            if (HEIGHT < WIDTH) {
                gl.glTranslatef((WIDTH - HEIGHT) / 2, 0, 0);
            }
            if (HEIGHT > WIDTH) {
                gl.glTranslatef(0, (HEIGHT - WIDTH) / 2, 0);
            }
     
        }
     
        // called for OpenGL rendering every reshape
     
        public void display(GLAutoDrawable drawable) {
     
            // limpiar la pantalla
            gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            /* El color de limpiado ser� cero */
            gl.glClearDepth(1.0);
            gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
     
            if (visualizeAxis) {
                DrawAxis ejes = new DrawAxis();
                ejes.drawObject(gl);
            }
     
            if (exercise == A) {
                drawExerciseA();
            }
     
     
            if (exercise == B) {
                drawExerciseB();
            }
     
            if(exercise == C)
            {
     
                drawTDelanuay();
     
            }
            if(exercise == D)
            {
                try
                {
                    drawTDelanuay2();
                } catch (InterruptedException ex)
                {
                    System.out.println(ex.getMessage());
                }
            }
     
     
            gl.glFlush();
        }
     
        // called if display mode or device are changed
        public void displayChanged(GLAutoDrawable drawable, boolean modeChanged,
                boolean deviceChanged) {
        }
     
        public static void main(String[] args) {
            Draw.HEIGH = HEIGHT;
            Draw.WIDTH = WIDTH;
            Test frame = new Test("Prac1. Algoritmos Geometricos");
            frame.setSize(WIDTH, HEIGHT);
            frame.setVisible(true);
        }
     
        public void encontrarConvexo(Polygon pol)
        {
            boolean encontrado = false;
            int cont = 0;
            Point p = pc.getPoint(cont);
            int i = 0;
            int j = 1;
            while(!encontrado)
            {
                if(p.classify(pol.getVertexAt(i), pol.getVertexAt(j)) == PointClassification.RIGHT)
                {
                    encontrado = true;
                    pol.add(p, j);
     
                }else{
     
                    cont++;
                    if(cont == POINT_CLOUD_VERT)
                    {
                        i = j;
                        j = (j+1)%pol.vertexSize();
                        cont = 0;
                    }
                    else
                    {
                       p = pc.getPoint(cont);   
                    }
     
                }
     
            }
            for(int w = 0; w < pol.vertexSize(); w++)
            {
                pol.set(pol.getVertexAt(w), w);
            }
        }
     
     
        public void mouseClicked(MouseEvent e)
        {
     
        }
     
     
        public void mousePressed(MouseEvent e)
        {
           System.out.println("Pulsado el boton del raton: "+e.getButton());
        }
     
     
        public void mouseReleased(MouseEvent e)
        {
     
        }
     
     
        public void mouseEntered(MouseEvent e)
        {
     
        }
     
     
        public void mouseExited(MouseEvent e)
        {
     
        }
     
     
        public void keyTyped(KeyEvent e)
        {
        }
     
     
        public void keyPressed(KeyEvent e)
        {
            switch (e.getKeyChar()) {
                        case 'E':
                        case 'e':
                            visualizeAxis = !visualizeAxis;
                            canvas.repaint();
                            break;
                        case 'a':
                        case 'A':
                            exercise = A;
                            break;
                        case 'b':
                        case 'B':
                            exercise = B;
                            break;
                        case 'c':
                        case 'C':
                            exercise = C;
                            break;
                        case 'd':
                        case 'D':
                            exercise = D;
                            break;
                        case 27: // esc
                            System.exit(0);
                    }
        }
     
     
        public void keyReleased(KeyEvent e)
        {
        }
     
    }

  2. #2
    Member
    Join Date
    Sep 2018
    Location
    Virginia
    Posts
    284
    My Mood
    Cool
    Thanks
    0
    Thanked 38 Times in 36 Posts

    Default Re: MouseListener doesn't work and It blocks KeyListener

    I don't see anything that you're doing wrong. And I don't have OpenGL so I can't run your program. If you provide me a location for the version of the OpenGL I can see how it performs. Also include the imports in your program. In the meantime, you can shorten your a little code by doing the following:

    Instead of this.

    public void mouseClicked(MouseEvent e)
        {
     
        }
     
     
        public void mousePressed(MouseEvent e)
        {
           System.out.println("Pulsado el boton del raton: "+e.getButton());
        }
     
     
        public void mouseReleased(MouseEvent e)
        {
     
        }
     
     
        public void mouseEntered(MouseEvent e)
        {
     
        }
     
     
        public void mouseExited(MouseEvent e)
        {
     
        }
     
     
        public void keyTyped(KeyEvent e)
        {
        }

    Create a private inner class for your main program.

        private class MyMouseListener extends MouseAdapter {
              public void mousePressed(MouseEvent e)
        {
           System.out.println("Pulsado el boton del raton: "+e.getButton());
        }
        }

    The MouseAdapter class has all the empty methods declared so you don't have too. It also includes empty methods
    for MoustMotionListener.

    Make the following changes.

    addMouseListener(new MyMouseListener());

    Normally it is considered best practice to use an instance of JFrame and not extend it. But my main question is why are you using Frame instead of JFrame?

    Regards,
    Jim

Similar Threads

  1. [SOLVED] Multiple Catch Blocks
    By thecoderr in forum Java Theory & Questions
    Replies: 3
    Last Post: October 19th, 2017, 08:30 PM
  2. Stanford CS106a Assignment 2: Pyramid Blocks
    By zammtech in forum What's Wrong With My Code?
    Replies: 15
    Last Post: November 19th, 2013, 07:29 PM
  3. Representing tones visually in blocks
    By Nindustries in forum Java Theory & Questions
    Replies: 9
    Last Post: January 20th, 2013, 01:49 PM
  4. [SOLVED] implements MouseListener doesn't work why
    By voltaire in forum AWT / Java Swing
    Replies: 2
    Last Post: May 1st, 2010, 04:30 PM
  5. Nested try blocks
    By Ahmed. in forum Member Introductions
    Replies: 2
    Last Post: April 30th, 2010, 08:12 AM