2012-12-20 55 views
0

有沒有辦法在PopupMenu(使用TrayIcon)渲染像JPanel這樣的圖形?我知道這可以通過使用JPopupMenu,但我不喜歡彈出不會關閉,如果我點擊它之外(和圖標不突出像PopupMenu一樣)。什麼我試圖用的JPopupMenu做PoppaMenu內部的JPanel

例子:

if(SystemTray.isSupported()) { 
     // Get the SystemTray instance 
     SystemTray tray = SystemTray.getSystemTray(); 

     // Load icon 
     Image image = new ImageIcon(this.getClass().getResource("delete.png")).getImage(); 

     final JPopupMenu popup = new JPopupMenu(); 
     popup.add(new JMenuItem("Test")); 

     JPanel p1 = new JPanel(); 
     p1.setBackground(Color.red); 
     p1.setPreferredSize(new Dimension(200, 300)); 
     popup.add(p1); 

     JTrayIcon trayIcon = new JTrayIcon(image); 
     trayIcon.setJPopupMenu(popup); 

     trayIcon.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mouseReleased(MouseEvent e) { 
       popup.setLocation(e.getX(), e.getY()); 
       popup.setInvoker(popup); 
       popup.setVisible(true); 
      } 
     }); 

     try { 
      tray.add(trayIcon); 
     } catch (Exception e) { 
      JOptionPane.showMessageDialog(null, "Could not add tray icon."); 
     } 
    } 

回答

0
You can extending JPopupMenu and add customItem to it: 
public class CustomPopUp extends JPopupMenu { 

    public CustomPopUp() { 
     reload(); 
    } 

    private void reload(final Collection<CustomItem> items) throws BadLocationException { 
     for (final CustomItem item : items) { 
      add(new AbstractAction(item.getLabel(), item.getIcon()) {    
       @Override 
       public void actionPerformed(final ActionEvent e) { 
        //do whatever 
       } 
      }); 
     } 

    } 
} 
public class CustomItem { 
    private String label; 
    private ImageIcon icon; 

    //getter and setter 
} 
1

有沒有辦法來渲染圖形像的JPanel的PopupMenu的?我知道 它可以通過使用JPopupMenu,但我不喜歡彈出 不會關閉,如果我點擊它外面(和圖標沒有得到 高亮與PopupMenu一樣)。

  • 我將只討論Java-2D直接彈出容器,確保有沒有問題,把JPanel與風俗畫,有JButtons,由GridLayout

  • 是的,有幾種方法奠定, the best describtion around by @Kirill Grouchnikov

  • 你可以決定你是否創建

    1)對於每個JPopupMenu/JMenu新塗料,

    2)投入到UIManager(然後有效期爲在當前JVM所有Objects

+0

一個使用JMenuItem的,這是不使用JPopupMenu時出現問題。問題是我想用TrayIcon顯示一個帶有圖形的彈出窗口。 –

+0

我只是從SystemTrays圖標談論JPopup的mousevents圖標 – mKorbel