direndd
direndd

Reputation: 652

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

Upvotes: 4

Views: 7634

Answers (3)

UdayKumar Mucharla
UdayKumar Mucharla

Reputation: 1

The problem with above code was you are creating new Mouse event with every click on the image.

// Create a Mouse pressed Event
mouseLis = new MouseAdapter() {
                        public void mousePressed(MouseEvent e) {
                            actionMenthod(e);
                        }
                   };

Here am attaching the my event to lblMap.

       lblMap.addMouseListener(mouseLis);

After this event happens you have to remove this event from the lblmap.

      lblMap.removeMouseListener(mouseLis);

After when I click again only one event will be there then it prints only once.

Upvotes: 0

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11940

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.

Upvotes: 6

smajlo
smajlo

Reputation: 972

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

Upvotes: 5

Related Questions