控件添加右键菜单项

以 JList 控件为例

首先控件需要添加鼠标的监听事件

1
2
3
4
5
6
7
8
mUserList.addMouseListener(new MouseAdapter() {

@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
showPopup(e);
}
});
showPopup() 显示菜单的功能
1
2
3
4
5
6
7
public void showPopup(MouseEvent e) {
if (e.isPopupTrigger() && mUserList.getSelectedIndex() != -1
&& !mUserList.getSelectedValue().equals("管理员")) {
Object selected = mUserName.getElementAt(mUserList.getSelectedIndex());
popupMenu.show(e.getComponent(), e.getX(), e.getY());
}
}
e.isPopupTrigger() 检测是否是右键,mUserList.getSelectedIndex() 防止在列表空白处点击