Question

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?

Was it helpful?

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);
    }
}

OTHER TIPS

You can add a MouseListener to your JApplet using the method:

public void addMouseListener(MouseListener l)

JApplet inherits this method from Component, as explained here.

My suggestion would be to put your MouseProcessing class as an inner class to MmmuhApplet, like so:

public class MmmuhApplet extends JApplet {
    int x, y;

    public MmmuhApplet(){
         addMouseListener(new MouseProcessing());
    }
    // stuff (...)

    private class MouseProcessing implements MouseListener, MouseMotionListener{

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

        // other methods (...)
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top