通过 addMouseListener 添加时如何检测鼠标点击 menuItem
考虑您想要使用“关闭应用程序”菜单项关闭 Java 应用程序。
3 种可能的解决方案是(使用 ActionListener 或 MouseAdapter 或 MouseListener):
menuItemClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
menuItemClose.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
menuItemClose.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
3 种解决方案,并且只有第一个会触发。
这又有何解释呢? 其他一些组件是否有相同的行为? 遇到此类事件如何正确处理?
Consider you want to close your java application using "Close application" menu item.
3 possible solutions are (using ActionListener or MouseAdapter or MouseListener):
menuItemClose.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
System.exit(0);
}
});
menuItemClose.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
System.exit(0);
}
});
menuItemClose.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
System.exit(0);
}
});
3 solutions, and only first one fires.
What is the explanation of this?
Does some other componenets have same behavior?
How to properly handle events in such cases?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,开发人员建议您使用
Action
< /a>“将功能和状态与组件分开。”No, the developers suggest that you use
Action
"to separate functionality and state from a component."在该示例中,您永远不会注册
KeyListener
。无论如何,您应该只注册一个ActionListener
。有关详细信息,请参阅处理菜单项中的事件。另请参阅:
In that example, you never register a
KeyListener
. Anyway, you should only register anActionListener
. For more information, see Handling Events from Menu Items.See also: