javaswingjappletmouse-listeners

Java: Access applet fields from MouseListener class


This is very, very stupid question. I'm supposed to implement mouse processing in seperate class and since I'm a total noob I have problems doing so the right way.

This is my main applet class:

public class MmmuhApplet extends JApplet {
    int x, y;

    // stuff (...)
}

And the additional class:

public class MouseProcessing implements MouseListener, MouseMotionListener{

    @Override
    public void mouseClicked(MouseEvent arg0) {
        // I want to pass arg0.getX() to variable x. How?
    }

    // other methods (...)
}

The only idea that comes to my mind is to store a reference to MmmuhApplet instance in MouseProcessing class and access x/y from there via said reference. Is it a good idea?


Solution

  • "The only idea that comes to my mind is to store a reference to MmmuhApplet instance in MouseProcessing class and access x/y from there via said reference. Is it a good idea?"

    You had the right idea. What you can do is pass the applet to the listener through constructor injection (or pass by reference). Then have setters for whatever fields you need. Something like

    public class MmmuhApplet extends JApplet {
        int x, y;
    
        public void inti() {
            addMouseListener(new MouseProcessing(MmmuhApplet.this));
        }
    
        public void setX(int x) {
            this.x = x;
        }
    
        public void setY(int y) {
            this.y = y;
        }
    }
    
    public class MouseProcessing implements MouseListener {
        private MmmuhApplet mmmuh;
    
        public MouseProcessing(MmmuhApplet mmmuh) {
            this.mmmuh = mmmuh;
        }
    
        public void mousePressed(MouseEvent e) {
            Point p = e.getPoint();
            mmmuh.setX(p.x);
            mmmuh.setY(p.y);
        }
    }