Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the dimension of a JPopupMenu?

I have a TrayIcon with a JPopupMenu attached to it. When I add a JMenuItem to the popup menu, I want to know the dimension of this popup menu. But the dimension is not calculated: getBounds(), getSize() and getVisibleRect() all return zero-by-zero dimensions.

As you can see in the image, the popup menu certainly has a dimension.
Tray Popup Menu
Now how can I get the dimension of the popup menu?

like image 544
MC Emperor Avatar asked Jan 17 '12 15:01

MC Emperor


1 Answers

Components don't have a size until they have been realized. Which basically means until they have been made visible (or packed).

Why is this important, the system looks after positioning the menu? If we know the requirement maybe we can provide a better solution.

If you want a hack then try using PopupMenuListener and handle the popupMenuWillBecomeVisible() event. Then you will need to wrap your code in a SwingUtilities.invokeLater() so the code executes after the menu is visible.

like image 188
camickr Avatar answered Oct 16 '22 19:10

camickr