不幸的是,Swing 不支持弹出上下文菜单。你必须自己动手。幸运的是,这并不难。也许最干净的方法是安装您自己的事件队列,如此处所述。那篇文章建议以下实现:
// @author Santhosh Kumar T - santhosh@in.fiorano.com
public class MyEventQueue extends EventQueue{
protected void dispatchEvent(AWTEvent event){
super.dispatchEvent(event);
// interested only in mouseevents
if(!(event instanceof MouseEvent))
return;
MouseEvent me = (MouseEvent)event;
// interested only in popuptriggers
if(!me.isPopupTrigger())
return;
// me.getComponent(...) retunrs the heavy weight component on which event occured
Component comp = SwingUtilities.getDeepestComponentAt(me.getComponent(), me.getX(), me.getY());
// interested only in textcomponents
if(!(comp instanceof JTextComponent))
return;
// no popup shown by user code
if(MenuSelectionManager.defaultManager().getSelectedPath().length>0)
return;
// create popup menu and show
JTextComponent tc = (JTextComponent)comp;
JPopupMenu menu = new JPopupMenu();
menu.add(new CutAction(tc));
menu.add(new CopyAction(tc));
menu.add(new PasteAction(tc));
menu.add(new DeleteAction(tc));
menu.addSeparator();
menu.add(new SelectAllAction(tc));
Point pt = SwingUtilities.convertPoint(me.getComponent(), me.getPoint(), tc);
menu.show(tc, pt.x, pt.y);
}
}
然后,您可以将其用于:
public static void main(String[] args){
Toolkit.getDefaultToolkit().getSystemEventQueue().push(new MyEventQueue());
.....
}
使用那一行代码,您可以在应用程序中的每个文本组件上获得一个弹出菜单。
动作类并不太复杂。例如,下面是粘贴操作的实现,它显示了与系统剪贴板的交互:
// @author Santhosh Kumar T - santhosh@in.fiorano.com
class PasteAction extends AbstractAction{
JTextComponent comp;
public PasteAction(JTextComponent comp){
super("Paste");
this.comp = comp;
}
public void actionPerformed(ActionEvent e){
comp.paste();
}
public boolean isEnabled(){
if (comp.isEditable() && comp.isEnabled()){
Transferable contents = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(this);
return contents.isDataFlavorSupported(DataFlavor.stringFlavor);
}else
return false;
}
}
有关其他操作实现的代码,请参阅文章。