MouseListener多次调用 [英] MouseListener called multiple times

查看:187
本文介绍了MouseListener多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用此代码来获取放置为jLable图标的图像的X和Y坐标. 对此

I am using this code to get the X and Y coordinates of an image placed as icon of a jLable. This method to get the coordinates was suggested by an answer to this question.

private void lblMapMouseClicked(java.awt.event.MouseEvent evt) {                                    
            lblMap.addMouseListener(new MouseAdapter() {
                public void mouseClicked(MouseEvent e) {
                    double X = e.getX();
                    double Y = e.getY();
                    System.out.println("X: " + X + "Y: " + Y );
                }
            });
    }   

当我运行此命令时,public void mouseClicked(MouseEvent e) { }被多次调用. 确实是我点击图片的次数.

When I run this public void mouseClicked(MouseEvent e) { } gets called multiple times. Exactly the amount of times I click on the image.

例如:如果我第三次单击它, System.out.println行中的X和Y值被打印3次.

Eg: If I'm clicking on it for the 3rd time , X and Y values from the System.out.println line , gets printed 3 times.

并且它随着我单击次数的增加而增加. 你们中的任何人都可以解释为什么会这样吗?我该如何解决? :)

And it increases as the number of times I click increases. Can any of you explain why this happens? And how can I fix it? :)

推荐答案

问题是您在单击时一次又一次地添加新的侦听器.

The problem is that you are adding a new listener again and again when click happens, here.

private void lblMapMouseClicked(MouseEvent evt) 
{
    lblMap.addMouseListener(new MouseAdapter()
    {
        ...

相反,将您的代码更改为此.

Instead, change your code to this.

private void lblMapMouseClicked(MouseEvent e)
{
    double X = e.getX();
    double Y = e.getY();
    System.out.println("X: " + X + "Y: " + Y);
}

它应该可以解决问题.

希望这会有所帮助.

这篇关于MouseListener多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆