package itheima005; import java.awt.*; import java.awt.event.*; public class popupmenuDemo { public static void main(String[] args) { new popupmenuDemo().init(); } Frame frame = new Frame("测试popupMenu"); TextArea ta = new TextArea("我爱中华", 6, 30); Panel p = new Panel(); PopupMenu popupMenu = new PopupMenu(); MenuItem comment = new MenuItem("注释"); MenuItem cancel = new MenuItem("取消注释"); MenuItem copy = new MenuItem("复制"); MenuItem save = new MenuItem("保存"); Menu save2 = new Menu("保存在"); private void init() { ActionListener actionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ta.append("点击了" + e.getActionCommand() + "\n"); } }; frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); comment.addActionListener(actionListener); cancel.addActionListener(actionListener); copy.addActionListener(actionListener); save.addActionListener(actionListener); //组装视图 popupMenu.add(comment); popupMenu.add(cancel); popupMenu.add(copy); save2.add(save); popupMenu.add(save2); p.setPreferredSize(new Dimension(200, 300)); //监听鼠标右键释放 p.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { boolean flag = e.isPopupTrigger(); if(flag){ popupMenu.show(p,e.getX(),e.getY()); } } }); p.add(popupMenu); // frame.add(ta); frame.add(p,BorderLayout.SOUTH); frame.pack(); frame.setVisible(true); } }