Move Popup Within Bounds of Client Window

Here is a script I developed some time ago for this purpose:

# Developed to be called from a popup window's internalFrameActivated event handler

# Import the necessary Javax Swing classes
from javax.swing import JFrame,SwingUtilities

# Get an unambiguous reference to the 'popupWindow' component from the event source
popupWindow = event.source

# Find the nearest ancestor JFrame of the 'popupWindow' component which will be the parent window that the popup was opened from
parentJFrame = SwingUtilities.getAncestorOfClass(JFrame, popupWindow)

# Set a margin value for positioning the 'popupWindow'
parentJFrameMargin = 100

# Try to get the mouse position relative to the 'parent' JFrame
try:
	popupWindowX = parentJFrame.getMousePosition(True).x
	popupWindowY = parentJFrame.getMousePosition(True).y
	
# If an exception occurs (e.g., mouse position not available), set default values of (0,0) [Upper left corner] plus the specified margin
except:
	popupWindowX = parentJFrameMargin
	popupWindowY = parentJFrameMargin
	
# Ensure that the 'popupWindow' is within the boundaries of the 'parent' JFrame
if popupWindowX < parentJFrameMargin:
	popupWindowX = parentJFrameMargin
elif popupWindowX + popupWindow.width > parentJFrame.width - parentJFrameMargin:
	popupWindowX = parentJFrame.width - popupWindow.width - parentJFrameMargin
if  popupWindowY < parentJFrameMargin:
	popupWindowY = parentJFrameMargin
elif popupWindowY + popupWindow.height > parentJFrame.height - parentJFrameMargin:
	popupWindowY = parentJFrame.height - popupWindow.height - parentJFrameMargin 
	
# Set the new location of the 'popupWindow' based on the calculated positions
popupWindow.setLocation(popupWindowX, popupWindowY)

It finds the Jframe of the window the popup was launched from, and calculates if the window can be positioned at the mouse cursor without overlapping the side of the window. If it can't be done, it positions it as close as possible. It also has an adjustable margin parameter which is currently set to 100 pixels, so the window will actually be contained within a 100 pixels of the edge of the parent window.

2 Likes