MC Emperor
MC Emperor

Reputation: 23017

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?

Upvotes: 5

Views: 773

Answers (3)

TotoliciCristian
TotoliciCristian

Reputation: 327

I have another solution to this problem. You can call show() method twice.

After you call the method first the dimension properties will be initialized, the second time you show the popup menu at the desired location. Here is an example:

I want to display the menu next to the button to do this I need to know the width to the popmenu enter image description here

If I call menu.getWidth() in the first time it will return 0 after the first call it will return the value ocupied by the popup menu;

int firstX = refreshButton.getLocation().x;
int firstY = refreshButton.getLocation().y;
menu.show(toolBar, firstX, firstY);
menu.show(toolBar, firstX -  menu.getWidth(), firstY);

Upvotes: 0

Neumi
Neumi

Reputation: 1

I was looking into this because i wanted to use a JPopupMenu for my TrayIcon instead of a AWT PopupMenu. Since a JPopupMenu has no pack(), the method from above will work of course. If it's just a simple menu without heavy graphics load, you can trick the system, by simply making the menu visible for a short moment after adding the menus:
myjPop.setVisible(true);
myjPop.setVisible(false);
After this you have the size of the menu. It's not the best solution ever, but it's simple and does the trick.

Upvotes: 0

camickr
camickr

Reputation: 324147

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.

Upvotes: 5

Related Questions