Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MouseListener called multiple times

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

like image 564
direndd Avatar asked Dec 20 '22 21:12

direndd


1 Answers

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.

like image 121
Sri Harsha Chilakapati Avatar answered Dec 28 '22 09:12

Sri Harsha Chilakapati