JPopupMenu和JMenuItem的定义:
//聊天信息JTextPane的右键弹出菜单
private JPopupMenu msgInfoPopMenu = null;
private JMenuItem copyItem = new JMenuItem("复制");
private JMenuItem selectAllItem = new JMenuItem("选择全部");
private JMenuItem clearItem = new JMenuItem("清屏");
注意:JTextPane一定要注册监听器
在右键弹出菜单:
if (e.getSource() == msgShowTxtPane && e.getButton() == MouseEvent.BUTTON3 && e.getClickCount() == 1) {
//这样处理是防止msgInfoPopMenu加入多次Item
if (msgInfoPopMenu == null) {
msgInfoPopMenu = new JPopupMenu();
} else {
msgInfoPopMenu.removeAll();
}
copyItem.addActionListener(this);
selectAllItem.addActionListener(this);
clearItem.addActionListener(this);
msgInfoPopMenu.add(copyItem);
msgInfoPopMenu.add(selectAllItem);
//分割线
msgInfoPopMenu.addSeparator();
msgInfoPopMenu.add(clearItem);
//显示的位置
msgInfoPopMenu.show(e.getComponent(), e.getX(), e.getY());
}
setIcon()可以设置Item的图片。
JMenuItem的事件跟JButton的事件一样处理。