Search code examples
javaswingpopupawtsystem-tray

How to add submenu to MenuItem


I'm trying to add submenu to a MenuItem which exists in a popup menu in system tray. Is there any way to achieve this? I've found some solutions about submenus but they use JMenuItem, and TrayIcon only accepts PopupMenu which only accepts MenuItems.

Trying to achieve this with MenuItem:

Image


Solution

  • A JMenuItem doesn't support submenus, you need to use another JMenu (add to you JPopupMenu). See How to Use Menus for more details

    For example...

    enter image description here

    JPopupMenu popupMenu = new JPopupMenu();
    
    JMenu deviceMenu = new JMenu("Add Device");
    deviceMenu.add(new JMenuItem("Add More..."));
    
    popupMenu.add(deviceMenu);
    popupMenu.add(new JMenuItem("Delete Device"));
    popupMenu.add(new JMenuItem("Fire"));
    popupMenu.add(new JMenuItem("Fault"));
    popupMenu.add(new JMenuItem("Supress"));
    

    (obviously, you'll still need to plugin functionality for all of this)

    and TrayIcon only accepts PopupMenu which only accepts MenuItems.

    There's a trick, you have to cheat a little, take a look at How do I get a PopupMenu to show up when I left-click on a TrayIcon in Java? for an example