views:

168

answers:

3

Hello,

I'm curious why I got the "right" BUT "wrong"number of result when I click the mouse. I supposed to print on the console mouseClicked once everytimes the mouse is clicked. However I got many of them printed out everytimes I clicked the mouse ...sometimes 5 e.g.

mouseClicked
mouseClicked
mouseClicked
mouseClicked
mouseClicked

Instead of just

mouseClicked

Why?

public class GUI extends JFrame implements MouseListener, ActionListener {
.....
   public GUI {
      GridBagLayout m = new GridBagLayout();
      Container c = getContentPane();
      c.setLayout (m);
      GridBagConstraints con = new GridBagConstraints();
      ....
      JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
      con = new GridBagConstraints();
      ...
      m.setConstraints(pDraw, con);

      pDraw.addMouseListener(this);     
      pack();         
      setVisible(true);       
   }

   public void mouseClicked(MouseEvent arg0) {
      System.out.println("mouseClicked");       
   }
}
+1  A: 

Have a look at this method in MouseEvent:

getClickCount

public int getClickCount() Returns the number of mouse clicks associated with this event. Returns: integer value for the number of clicks

Bozhidar Batsov
I tried the if(e.getClickCount()==1) but I still get many results
Jessy
+1  A: 

The example you provided looks correct and should work.

Since you're implementing the MouseListener interface, you might want to check if you're not accidentally printing "mouseClicked" in the mousePressed/mouseReleased methods.

Frederik
A: 

Thanks for all comments, since I did not implement all methods of mouseEvent, I should use new mouseAdapter() so that it doesn't mixed between mousepressed and mouseClicked.

public class GUI extends JFrame implements MouseListener, ActionListener {
.....
   public GUI {
      GridBagLayout m = new GridBagLayout();
      Container c = getContentPane();
      c.setLayout (m);
      GridBagConstraints con = new GridBagConstraints();
      ....
      JPanel pDraw = new JPanel(new GridLayout(ROWS,COLS,2,2)); 
      con = new GridBagConstraints();
      ...
      m.setConstraints(pDraw, con);

      pDraw.addMouseListener(new MouseAdapter(){
         public void mouseClicked(MouseEvent e) { 
            System.out.println("mouseClicked");
         } 
      });

      pack();         
      setVisible(true);       
   }
}
Jessy