MouseListener called multiple times

2019-06-26 16:29发布

问题:

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