java弹出式菜单
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。