RelativePoint (@NotNull JComponent component) { Point popupMenuPoint = null; final Rectangle visibleRect = component.getVisibleRect(); if (component instanceof JList<?> list) { // JList int firstVisibleIndex = list.getFirstVisibleIndex(); int lastVisibleIndex = list.getLastVisibleIndex(); int[] selectedIndices = list.getSelectedIndices(); for (int index : selectedIndices) { if (firstVisibleIndex <= index && index <= lastVisibleIndex) { Rectangle cellBounds = list.getCellBounds(index, index); popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 4, cellBounds.y + cellBounds.height - 1); break; } } } else if (component instanceof JTree tree) { // JTree TreePath[] paths = tree.getSelectionPaths(); if (paths != null && paths.length > 0) { TreePath pathFound = null; int distanceFound = Integer.MAX_VALUE; int center = visibleRect.y + visibleRect.height / 2; for (TreePath path : paths) { Rectangle bounds = tree.getPathBounds(path); if (bounds != null) { int distance = Math.abs(bounds.y + bounds.height / 2 - center); if (distance < distanceFound) { popupMenuPoint = new Point(bounds.x + 2, bounds.y + bounds.height - 1); distanceFound = distance; pathFound = path; } } } if (pathFound != null) { TreeUtil.scrollToVisible(tree, pathFound, false); } } } else if (component instanceof JTable table) { int column = table.getColumnModel().getSelectionModel().getLeadSelectionIndex(); int row = Math.max(table.getSelectionModel().getLeadSelectionIndex(), table.getSelectionModel().getAnchorSelectionIndex()); Rectangle rect = table.getCellRect(row, column, false); if (!visibleRect.intersects(rect)) { table.scrollRectToVisible(rect); } popupMenuPoint = new Point(rect.x, rect.y + rect.height - 1); } else if (component instanceof PopupOwner popupOwner) { JComponent popupComponent = popupOwner.getPopupComponent(); if (popupComponent == null || popupComponent == popupOwner) { popupMenuPoint = ((PopupOwner)component).getBestPopupPosition(); } else { popupMenuPoint = guessBestPopupLocation(popupComponent).getPoint(component); } } if (popupMenuPoint == null) { popupMenuPoint = new Point(visibleRect.x + visibleRect.width / 2, visibleRect.y + visibleRect.height / 2); } return new RelativePoint(component, popupMenuPoint); }