JPopupMenu的執行看起來有一些別扭:我們必須調用enableEvents()方法並選擇鼠標事件代替利用事件接收器。它可能增加一個鼠標接收器但MouseEvent從isPopupTrigger()處不會返回真值——它不知道將激活一個彈出菜單。另外,當我們嘗試接收器方法時,它的行為令人不可思議,這或許是鼠標單擊活動引起的。在下面的程序例子裡一些事件產生了這種彈出行為:
//: Popup.java // Creating popup menus with Swing package c13.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; public class Popup extends JPanel { JPopupMenu popup = new JPopupMenu(); JTextField t = new JTextField(10); public Popup() { add(t); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e){ t.setText( ((JMenuItem)e.getSource()).getText()); } }; JMenuItem m = new JMenuItem("Hither"); m.addActionListener(al); popup.add(m); m = new JMenuItem("Yon"); m.addActionListener(al); popup.add(m); m = new JMenuItem("Afar"); m.addActionListener(al); popup.add(m); popup.addSeparator(); m = new JMenuItem("Stay Here"); m.addActionListener(al); popup.add(m); PopupListener pl = new PopupListener(); addMouseListener(pl); t.addMouseListener(pl); } class PopupListener extends 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()); } } } public static void main(String args[]) { Show.inFrame(new Popup(),200,150); } } ///:~
相同的ActionListener被加入每個JMenuItem中,使其能從菜單標簽中取出文字,並將文字插入JTextField。