import java.awt.Window; //导入方法依赖的package包/类
private Point calculatePosition(Component source) {
int xSource = source.getLocationOnScreen().x;
int ySource = source.getLocationOnScreen().y;
// get size of popup
Dimension popupSize = ((Component) popupComponent).getSize();
if (popupSize.width == 0) {
popupSize = ((Component) popupComponent).getPreferredSize();
}
int xPopup = 0;
int yPopup = 0;
// get max x and y window positions
Window focusedWindow = KeyboardFocusManager.getCurrentKeyboardFocusManager().getActiveWindow();
int maxX = focusedWindow.getLocationOnScreen().x + focusedWindow.getWidth();
int maxY = focusedWindow.getLocationOnScreen().y + focusedWindow.getHeight();
switch (position) {
case VERTICAL:
// place popup at sources' x position
xPopup = xSource;
// check if popup is outside active window
if (xPopup + popupSize.width > maxX) {
// move popup x position to the left
// to fit inside the active window
xPopup = maxX - popupSize.width - BORDER_OFFSET;
}
// place popup always below source (to avoid overlapping)
yPopup = ySource + source.getHeight();
// if the popup now would be moved outside of RM Studio to the left it would look
// silly, so in that case just show it at its intended position and let it be cut
// off on the right side as we cannot do anything about it
if (xPopup < focusedWindow.getLocationOnScreen().x
|| (xPopup - focusedWindow.getLocationOnScreen().x) + popupSize.width > focusedWindow.getWidth()) {
xPopup = xSource;
}
break;
case HORIZONTAL:
// place popup always to the right side of the source (to avoid overlapping)
xPopup = xSource + source.getWidth();
yPopup = ySource;
// check if popup is outside active window
if (yPopup + popupSize.height > maxY) {
// move popup upwards to fit into active window
yPopup = maxY - popupSize.height - BORDER_OFFSET;
}
// if the popup now would be moved outside of RM Studio at the top it would look
// silly, so in that case just show it at its intended position and let it be cut
// off on the bottom side as we cannot do anything about it
if (yPopup < focusedWindow.getLocationOnScreen().y
|| (yPopup - focusedWindow.getLocationOnScreen().y) + popupSize.height > focusedWindow.getHeight()) {
yPopup = ySource;
}
break;
}
return new Point(xPopup, yPopup);
}