注释很详细,直接上代码
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class swing_test_17 {
private Frame frame=new Frame("测试PopupMenu");
//创建文本域
private TextArea ta=new TextArea("遥遥领先!",6,40);
//创建Panel容器
private Panel p=new Panel();
//创建PopupMenu
PopupMenu popupMenu=new PopupMenu();
//创建菜单项
MenuItem comment=new MenuItem("注释");
MenuItem cancelcomment=new MenuItem("取消注释");
MenuItem copy=new MenuItem("复制");
MenuItem save=new MenuItem("保存");
//组装视图
public void init() {
//创建监听器
ActionListener listener=new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand=e.getActionCommand();
ta.append("您点击了:"+actionCommand+"\n");
}
};
//注册监听器
comment.addActionListener(listener);
cancelcomment.addActionListener(listener);
copy.addActionListener(listener);
save.addActionListener(listener);
//设置菜单项的内容
popupMenu.add(comment);
popupMenu.add(cancelcomment);
popupMenu.add(copy);
popupMenu.add(save);
//将PopupMenu添加到Panel容器中
p.add(popupMenu);
//用setPreferredSize设置Panel的大小
p.setPreferredSize(new Dimension(400,300));
//给Panel注册鼠标事件,监听鼠标释放动作
p.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
boolean isPopupTrigger=e.isPopupTrigger();
if(isPopupTrigger) {
//显示PopupMenu
if(p!=null) {
popupMenu.show(p, e.getX(), e.getY());
}
}
}
});
frame.add(p,BorderLayout.SOUTH);
frame.add(ta,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
new swing_test_17().init();
}
}
演示效果: