How to get a list of all JPopupMenu components currently shown on the screen.
Or get all JPopupMenu components that then could be filtered by visibility, validity etc.
I need this for writing tests. Stuck on JPopupMenu-s is not part of parent-child (container-component) relations.
For all unit tests with swing we use the Fest framework. There is a popup menu fixture that will allow you to test stuff on the popup menu.
https://github.com/alexruiz/fest-swing-1.x
Using the framework I am sure you can search for all popup menus shown by searching with the name you set for the JPopupMenu.
EDIT: The framework maintenance changed hands a few years ago. Please check before using it.
As comments show this is not trivial as effected by light and heavyweight concerns... For example in some cases JPopupMenu can be nested inside a JRootPane. However this in an alternative public API that be used - javax.swing.MenuSelectionManager which can be used to get list of JPopupMenus. I found this inside javax.swing.plaf.basic.BasicPopupMenuUI.getPopups()
static List<JPopupMenu> getPopups() {
MenuSelectionManager msm = MenuSelectionManager.defaultManager();
MenuElement[] p = msm.getSelectedPath();
List<JPopupMenu> list = new ArrayList<JPopupMenu>(p.length);
for (MenuElement element : p) {
if (element instanceof JPopupMenu) {
list.add((JPopupMenu) element);
}
}
return list;
}
Original solution using Window.getWindows()
private boolean isPopupMenuOpen() {
for (Window each : Window.getWindows()) {
if (findPopup(each) != null) {
return true;
}
}
return false;
}
private JPopupMenu findPopup(Component root) {
if (root instanceof JPopupMenu) {
return (JPopupMenu) root;
}
if (root instanceof JWindow) {
return findPopup(((JWindow)root).getContentPane());
}
if (root instanceof JRootPane) {
return findPopup(((JRootPane)root).getLayeredPane());
}
if (root instanceof Container) {
for (Component each : ((Container) root).getComponents()) {
return findPopup(each);
}
}
return null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With