import java.awt.*; import java.awt.event.*; import javax.swing.*; public class PopupMenuDemo extends MouseAdapter implements ActionListener { JFrame frame=new JFrame("Popup Menu Demo"); JPopupMenu popup=new JPopupMenu(); JTextField tf=new JTextField(); JLabel label=new JLabel("Try to click left and right button"); public static void main(String args[]) { PopupMenuDemo popupMenuDemo=new PopupMenuDemo(); popupMenuDemo.go(); } public void go() { JMenuItem menuItem=new JMenuItem("New",KeyEvent.VK_N); menuItem.addActionListener(this); popup.add(menuItem); menuItem=new JMenuItem("Load",KeyEvent.VK_L); menuItem.addActionListener(this); popup.add(menuItem); popup.addSeparator(); menuItem=new JMenuItem("Copy",KeyEvent.VK_C); menuItem.addActionListener(this); popup.add(menuItem); menuItem=new JMenuItem("Cut",KeyEvent.VK_T); menuItem.addActionListener(this); popup.add(menuItem); menuItem=new JMenuItem("Paste",KeyEvent.VK_P); menuItem.addActionListener(this); popup.add(menuItem); menuItem=new JMenuItem("Exit",KeyEvent.VK_E); popup.add(menuItem); menuItem.addActionListener(this); label.addMouseListener(this); tf.setEditable(false); Container cp=frame.getContentPane(); cp.add(label,BorderLayout.CENTER); cp.add(tf,BorderLayout.SOUTH); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300,200); frame.setVisible(true); } //改写MouseAdapter中的方法 public void mousePressed(MouseEvent e) { maybeShowPopup(e); } public void mouseReleased(MouseEvent e) { maybeShowPopup(e); } private void maybeShowPopup(MouseEvent e){ if(e.isPopupTrigger()) { popup.show(e.getComponent(), e.getX(),e.getY()); } } //实现ActionListener接口中的方法 public void actionPerformed(ActionEvent e) { tf.setText(e.getActionCommand()); if(e.getActionCommand()=="Exit") { System.exit(0); } } }