获得鼠标单击事件的正确结果

时间:2010-04-06 13:05:33

标签: java events mouse awt

我很好奇为什么当我点击鼠标时我得到了“正确”但“错误”的结果数。 每次点击鼠标时,我都应该在控制台上mouseClicked 打印一次。然而,每当我点击鼠标时,我都会打印出许多...有时候5个。

mouseClicked
mouseClicked
mouseClicked
mouseClicked
mouseClicked

而不仅仅是

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(this);     
      pack();         
      setVisible(true);       
   }

   public void mouseClicked(MouseEvent arg0) {
      System.out.println("mouseClicked");       
   }
}

3 个答案:

答案 0 :(得分:1)

在MouseEvent中查看此方法:

getClickCount

public int getClickCount() 返回与此事件关联的鼠标单击次数。 返回: 点击次数的整数值

答案 1 :(得分:1)

您提供的示例看起来正确,应该工作。

由于您正在实现MouseListener接口,因此您可能需要检查是否在mousePressed / mouseReleased方法中不小心打印“mouseClicked”。

答案 2 :(得分:0)

感谢所有评论,因为我没有实现mouseEvent的所有方法,我应该使用new mouseAdapter(),以便它不会在mousepressed和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);       
   }
}