2

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

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
John Matters
  • 39
  • 1
  • 9

2 Answers2

5

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

Community
  • 1
  • 1
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • Hi. I know I've accepted this answer but I have a problem. The menu appears, but the menu items don't get highlighted when I hover the mouse on them, also the menu doesn't disappear when I click out of it. Do you have any idea? – John Matters Jul 02 '15 at 10:53
  • From memory, the menus highlight ok for me, but I'll have to test it. You may be required to force the popup menu closed manually, as it's not really attached to any thing... – MadProgrammer Jul 02 '15 at 10:55
  • I already added `popup.showVisible(false)` at the end of the listeners, but I don't know how to handle a mouse click out of it – John Matters Jul 02 '15 at 10:56
  • I "hack" the solution by placing a "close" option on the menu. The problem is, you have no context from which to detect a "focus lost" – MadProgrammer Jul 02 '15 at 11:12
1

Sure, you just add a Menu called "Add Device" to the PopupMenu (Menu is a subclass of MenuItem, so it can be added).

PopupMenu popupMenu = new PopupMenu();
Menu subMenu = new Menu("Add Device");
subMenu.add(new MenuItem("Add More .."));
popupMenu.add(subMenu);
Stefan Reich
  • 1,000
  • 9
  • 12