2013-02-07 82 views
3

我想在用戶右鍵單擊我的JTable時獲得JPopUpMenu顯示。在我的課堂延伸的JTable,我叫下面的代碼:Java在Mac OS中彈出菜單

addMouseListener(new MouseAdapter() 
    { 
     @Override 
     public void mouseReleased(MouseEvent e) 
     { 
      rowClicked = rowAtPoint(e.getPoint()); 
      colClicked = columnAtPoint(e.getPoint()); 
      if (e.isPopupTrigger()) 
      { 
       popUpMenu.show(e.getComponent(), e.getX(), e.getY()); 
      } 
     } 

     @Override 
     public void mouseClicked(MouseEvent e) 
     { 
      rowClicked = rowAtPoint(e.getPoint()); 
      colClicked = columnAtPoint(e.getPoint()); 

      if(e.isPopupTrigger()) 
      { 
       popUpMenu.show(e.getComponent(), e.getX(), e.getY()); 
      } 
     } 
    }); 

每當我右鍵點擊觸控板,用鼠標,或使用CTRL +右鍵,if(e.isPopupTrigger())從不計算真實,菜單是永遠所示。我在那裏有斷點來驗證。

我在網上做了一些研究,看來這個解決方案應該可以工作。由於右鍵單擊是依賴於平臺的,因此使用isPopupTrigger()應該是要走的路。

因爲我在Mac上,有什麼特別的嗎?

回答

4

這個簡單的例子適用於我,也許它會幫助你找到你的問題。我在Mac上使用Java 7中

enter image description here

public static void main(String[] args) 
{ 
    JFrame frame = new JFrame(); 
    JPanel panel = new JPanel(); 

    String columnNames[] = { "Column 1", "Column 2", "Column 3" }; 

    String dataValues[][] = { { "12", "234", "67" }, { "-123", "43", "853" }, { "93", "89.2", "109" }, { "279", "9033", "3092" } }; 
    JTable table = new JTable(dataValues, columnNames); 

    panel.add(table); 

    final JPopupMenu menu = new JPopupMenu(); 
    JMenuItem item = new JMenuItem("item"); 
    menu.add(item); 
    table.setComponentPopupMenu(menu); 

    table.addMouseListener(new MouseAdapter() 
    { 
     @Override 
     public void mouseReleased(MouseEvent e) 
     { 
      if (e.isPopupTrigger()) 
      { 
       menu.show(e.getComponent(), e.getX(), e.getY()); 
      } 
     } 

     @Override 
     public void mouseClicked(MouseEvent e) 
     { 
      if (e.isPopupTrigger()) 
      { 
       menu.show(e.getComponent(), e.getX(), e.getY()); 
      } 
     } 
    }); 

    frame.setContentPane(panel); 
    frame.pack(); 
    frame.setVisible(true); 
} 
+0

真棒,謝謝你,讓我試試這個 – user489041

+1

+1'setComponentPopupMenu()',也看到了[這裏](HTTP: //stackoverflow.com/a/5129757/230513)。 – trashgod

+0

通過添加解決我的問題的'setComponentPopupMenu'。感謝這個例子 – user489041