javaswingcoordinatesmouselistenermouse-listeners

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


Solution

  • 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.