无法在Java中获得鼠标位置

时间:2014-05-13 19:21:10

标签: java swing mouseevent

画类:

public class Paint extends JPanel implements ActionListener {
    Image swimmingpool;
    Mouse swim = new Mouse();
    Timer tm = new Timer(7, this);
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        System.out.println(swim.getdistance()); //prints out 0 ?!?


ImageIcon swimminghold = new ImageIcon(render.class.getResource("resources/Swimmingpoolns.png")); 
    swimmingpool = swimminghold.getImage();
    g.drawImage(swimmingpool, 0,-40,null); 
        if (swim.getdistance() >= 3) {
            System.out.println("test works");
        }
    }
    public void actionPerformed(ActionEvent e) {
        repaint();
    }

}

鼠标类

public class Mouse implements MouseMotionListener {
    private int x1 = 200;
    private int y1 = 165;
    double distance;
    public void mouseMoved(MouseEvent e) {


double distance1 = Math.pow((e.getX() - x1), 2);
        double distance2 = Math.pow((e.getY() - y1), 2);

        setdistance(Math.sqrt(distance1 + distance2));
        // The below prints, and has been
        // tested to print the correct distance
        System.out.println(getdistance());
    }
    public void setdistance(double distance) {
        this.distance = distance;
    }
    public double getdistance() {
        return distance;
    }
}

当我在Mouse类中执行System.out.println(getdistance())时,它会打印正确的距离,而如果我在paint类中执行System.out.println(swim.getdistance());则打印0

我尝试过的所有内容仍然会在课程distance = 0中产生public void paintComponent(Graphics g)

我不理解什么?

1 个答案:

答案 0 :(得分:1)

正如@ Hunter-mcmillen所指出的那样:你对java运算符感到困惑。

public  void  mouseMoved(MouseEvent e) { 

        double distance1 = Math.pow((e.getX() - x1),2);
        double distance2 = Math.pow((e.getY() - y1),2); // Math.pow(a,b) == a^b (in a calculator)

        setdistance(Math.sqrt(distance1 + distance2));
        System.out.println(getdistance()); 
}

我真的建议您在假设它们如何使用该语言之前仔细阅读Java operators

编辑2:

我还建议你为这张图片创建一个JPanel或JLabel,然后在这个新的Jpanel或Label或其他组件中加载这样的图片。

public class Paint extends JPanel implements ActionListener {
    Mouse swim = new Mouse();
    Timer tm = new Timer(7, this);
    public void paintComponent(Graphics g) {
    // Try this:
    ImageIcon swimminghold = new ImageIcon(render.class.getResource("resources/Swimmingpoolns.png")); 
    swimmingpool = swimminghold.getImage();
    JLabel label = new JLabel();
    label.setIcon(swimminghold);
    label.addMouseMotionListener(swim);
    addMouseMotionListener(swim);
    label.addMouseMotionListener(swim);
    addMouseMotionListener(swim);

        //Do something

        /* ...*/
}