简体   繁体   English

Java:从MouseListener类访问applet字段

[英]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. 我想到的唯一想法是将对MmmuhApplet实例的引用存储在MouseProcessing类中,并通过该引用从那里访问x / y。 Is it a good idea? 这是个好主意吗?

"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?" “我想到的唯一想法是将对MmmuhApplet实例的引用存储在MouseProcessing类中,并通过该引用从那里访问x / y。这是一个好主意吗?”

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

You can add a MouseListener to your JApplet using the method: 您可以使用以下方法将MouseListener添加到JApplet

public void addMouseListener(MouseListener l)

JApplet inherits this method from Component , as explained here . JApplet继承了这个方法Component ,如解释在这里

My suggestion would be to put your MouseProcessing class as an inner class to MmmuhApplet , like so: 我的建议是将MouseProcessing类作为内部类MmmuhApplet ,如下所示:

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 (...)
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM