日期:2014-05-20  浏览次数:20819 次

Swing JPopupMenu问题
关于Swing JPopupMenu的选择项返回值问题。。
Java code

JMenuItem copy = new JMenuItem("コピー");
JMenuItem paste = new JMenuItem("貼り付け");
copy.setEnabled(true);
peast.setEnabled(true);            
popupmenu.add(copy);
popupmenu.add(paste);
popupmenu.show(e.getComponent(), e.getX(), e.getY());

popupmenu.addPopupMenuListener(new PopupMenuListener() {

    public void popupMenuCanceled(PopupMenuEvent arg0) {}

    public void popupMenuWillBecomeInvisible(PopupMenuEvent arg0) {
                  
                  //我想在这里获得Popup选择的项
                  //如果选择Copy返回个东东
                  //如果选择paste也返回一个东西
        if (Copy){
                      //............................
                   }
                   if (paste){
                      //............................
                   }

    }

    public void popupMenuWillBecomeVisible(PopupMenuEvent arg0) {}
                        
});



------解决方案--------------------
Java code


final JMenuItem copy = new JMenuItem("コピー");
final JMenuItem paste = new JMenuItem("貼り付け");
copy.setEnabled(true);
peast.setEnabled(true);  

ActionListener listener = new ActionListener() {

  @Override
  public void actionPerformed(ActionEvent e) {
  
    Object source = e.getSource();
    if( source == copy ) {
      
      // ...
    }
    else if( source == paste ) {

      // ...
    }
  }
}

copy.addActionListener(listener);
paste.addActionListener(listener);

popupmenu.add(copy);
popupmenu.add(paste);

// ...