2012-12-20 32 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