获取鼠标单击事件的正确结果
我很好奇为什么当我单击鼠标时得到“正确”但“错误”的结果数。 我应该在每次单击鼠标时在控制台上打印 mouseClicked
once 。然而,每次我点击鼠标时,我都会打印出其中的许多内容...有时是 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");
}
}
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");
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
看看 MouseEvent 中的这个方法:
getClickCount
public int getClickCount()
返回与此事件关联的鼠标单击次数。
返回:
点击次数的整数值
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
您提供的示例看起来正确并且应该可以工作。
由于您正在实现 MouseListener 接口,因此您可能需要检查是否意外在 mousePressed/mouseReleased 方法中打印了“mouseClicked”。
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.
感谢所有评论,因为我没有实现 mouseEvent 的所有方法,所以我应该使用 new mouseAdapter() ,这样它就不会在 mousepressed 和 mouseClicked 之间混合。
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.