2012-04-30 35 views
2

我有一個JRadioButton併爲其設置了一個ComponentPopupMenu。JPopupMenuItem獲取觸發JPopupMenu的組件

JRadioButton rdbtnTest = new JRadioButton(); 
rdbtnTest.setComponentPopupMenu(popupMenu); 

的彈出菜單是一個JPopupMenu一個JPopupMenuItemJPopupMenuItem有一個MouseListener,所以在點擊鼠標時,打開一個網頁。

JPopupMenu popupMenu = new JPopupMenu("GO"); 
PopupMenuListener popupMenuListener = new MyPopupMenuListener(); 
popupMenu.addPopupMenuListener(popupMenuListener); 
MenuItem openMenuItem = new JMenuItem("Open Webpage"); 

openMenuItem.addMouseListener(new MouseListener() { 
     @Override 
     public void mousePressed(MouseEvent arg0) { 
      Component comp = arg0.getComponent(); // will only return the JPopupMenuItem 
      // Determine the right-clicked radio button and open webpage 
     } 
popupMenu.add(openMenuItem); 

我的問題是:如果我有另外一個JRadioButton rdbtnTest2用相同的彈出菜單,我能確定這兩個單選按鈕的觸發JPopupMenu的?打開網頁時,我需要根據右鍵單擊哪個單選按鈕來傳遞特定參數。

+0

+1使用'setComponentPopupMenu()'。 – trashgod

回答

3

當您在MouseListener中顯示彈出式菜單時,只需獲取事件源並將其存儲在某處(調用菜單的單選按鈕)。在你的代碼中,檢查彈出式調用器。