关于java中MouseEvent.isPopupTrigger()方法的使用问题
eclipse中对此方法的解释如下:
Returns whether or not this mouse event is the popup menu trigger event for the platform.
Note: Popup menus are triggered differently on different systems. Therefore,
isPopupTrigger
should be checked in bothmousePressed
andmouseReleased
for proper cross-platform functionality.Returns:
boolean, true if this event is the popup menu trigger for this platform
大致意思为:
如果该mouseEvent触发了平台中的popup menu,则返回true,否则返回false。需要注意的是:popup menu在不同系统中的触发条件并不相同。因此,为了正确实现跨平台功能,必须同时监听mousePressed(鼠标按下)和mouseReleased(鼠标释放)两个动作,以此来确保能够检测到isPopupTrigger。(具体代码见示例)
实战中在windows环境下,注释掉mousePressed方法,也可以触发popup menu,即只需要mouseReleased即可触发。
JPopupMenu jPopupMenuOne;
MouseListener popupListener = new PopupListener(jPopupMenuOne);
class PopupListener extends MouseAdapter{
JPopupMenu popupMenu;
public PopupListener(JPopupMenu popupMenu) {
this.popupMenu = popupMenu;
}
public void mousePressed(MouseEvent e) {
showPopupMenu(e);
}
public void mouseReleased(MouseEvent e) {
showPopupMenu(e);
}
private void showPopupMenu(MouseEvent e) {
if(e.isPopupTrigger()) {
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}