【问题标题】:JPanel inside PopupMenuPopupMenu 内的 JPanel
【发布时间】:2012-12-20 10:42:40
【问题描述】:

有没有办法在 PopupMenu(使用 TrayIcon)中呈现类似 JPanel 的图形?我知道使用 JPopupMenu 是可能的,但我不喜欢在弹出窗口外部单击时不会关闭(并且图标不会像 PopupMenu 那样突出显示)。

我尝试使用 JPopupMenu 的示例:

    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." );
        }
    }

【问题讨论】:

    标签: java swing java-2d jpopupmenu


    【解决方案1】:

    有没有办法在 PopupMenu 中渲染像 JPanel 这样的图形?我知道 使用 JPopupMenu 是可能的,但我不喜欢弹出窗口 如果我在它外部单击,它不会关闭(并且图标没有得到 与 PopupMenu 一样突出显示)。

    • 我将只谈论Java-2D 直接到弹出容器,确保将JPanel 与自定义绘画,JButtons,由GridLayout 铺设没有问题

    • 是的,有几种方法,the best describtion around by @Kirill Grouchnikov

    • 你可以决定是否创建

      1) 为JPopupMenu / JMenu 中的每一个提供一个新的油漆,

      2) 放入UIManager(然后对当前JVM 中的所有Objects 有效)

    【讨论】:

    • 那个使用 JMenuItem,使用 JPopupMenu 时这不是问题。问题是我想从 TrayIcon 显示一个带有图形的弹出窗口。
    • 我说的只是来自 SystemTrays Icon 的 JPopup 的 mousevents
    【解决方案2】:
    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
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多