Rectangle (@NotNull Dimension d, @NotNull Position @NotNull [] traversalPolicy) { if (traversalPolicy.length == 0) traversalPolicy = DEFAULT_POSITION_ORDER; Rectangle popupRect = null; Rectangle r = null; final List<Rectangle> boxes = new ArrayList<>(); for (Position position : traversalPolicy) { switch (position) { case TOP -> { r = positionAbove(d); boxes.add(crop(myScreenRect, new Rectangle(myRelativeOnScreen.x, myScreenRect.y, myScreenRect.width, getYForTopPositioning() - myScreenRect.y - myGap))); } case BOTTOM -> { r = positionUnder(d); boxes.add(crop(myScreenRect, new Rectangle(myRelativeOnScreen.x, myRelativeOnScreen.y + myRelativeTo.getHeight() + myGap, myScreenRect.width, myScreenRect.height))); } case LEFT -> { r = positionLeft(d); boxes.add(crop(myScreenRect, new Rectangle(myScreenRect.x, myRelativeOnScreen.y, myRelativeOnScreen.x - myScreenRect.x - myGap, myScreenRect.height))); } case RIGHT -> { r = positionRight(d); boxes.add(crop(myScreenRect, new Rectangle(myRelativeOnScreen.x + myRelativeTo.getWidth() + myGap, myRelativeOnScreen.y, myScreenRect.width, myScreenRect.height))); } } if (myScreenRect.contains(r)) { popupRect = r; break; } } if (popupRect != null) { return r; } else { // ok, popup does not fit, will try to resize it boxes.sort(Comparator.comparingInt((Rectangle o) -> o.width).thenComparingInt(o -> o.height)); final Rectangle suitableBox = boxes.get(boxes.size() - 1); return crop(suitableBox, new Rectangle( suitableBox.x < myRelativeOnScreen.x ? suitableBox.x + suitableBox.width - d.width : suitableBox.x, suitableBox.y < myRelativeOnScreen.y ? suitableBox.y + suitableBox.height - d.height : suitableBox.y, d.width, d.height )); } }