MouseListener called multiple times

青春壹個敷衍的年華 提交于 2019-12-10 17:38:54

问题


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

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

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? :)


回答1:


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

And it should fix the problem.

Hope this helps.




回答2:


it looks for me that every time image is clicked new mouse listener is added.. do also

 System.out.println(this)

to check from which instance of mouse listener it is actually printed



来源:https://stackoverflow.com/questions/19981336/mouselistener-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!