弹出式菜单JPopupMenu,需要用到鼠标事件。
MouseListener必须要实现所有接口,MouseAdapter是类,只写你关心的方法,即MouseAdapter实现了MouseListener中的方法
import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; public class Demo extends JFrame { public Demo() { setTitle("弹出式菜单"); setBounds(100, 100, 300, 200); setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); Container c = getContentPane(); JLabel label = new JLabel("请单击鼠标右键"); c.add(label, BorderLayout.CENTER); JPopupMenu popupMenu = new JPopupMenu();//弹出式菜单 JMenuItem copyItem=new JMenuItem("复制"); popupMenu.add(copyItem); JMenu pasteItem=new JMenu("粘贴"); popupMenu.add(pasteItem); JMenuItem pasteItem1=new JMenuItem("只粘贴文本"); JMenuItem pasteItem2=new JMenuItem("源格式粘贴"); pasteItem.add(pasteItem1); pasteItem.add(pasteItem2); //MouseListener必须要实现所有接口,MouseAdapter是类,只写你关心的方法,即MouseAdapter实现了MouseListener中的方法 c.addMouseListener(new MouseAdapter() {//为窗体顶层容器添加鼠标监听 public void mouseReleased(MouseEvent e) {//鼠标释放 if (e.isPopupTrigger()) {//判断鼠标事件是否是弹出菜单触发,若是则在释放鼠标的位置弹出菜单 popupMenu.show(e.getComponent(), e.getX(), e.getY()); } } }); } public static void main(String[] args) { Demo frame = new Demo(); frame.setVisible(true); } }