JBR-5824 Ensure popup menus are on the correct screen

This is a very old bug, JDK-6415065.

What happens here is that when the position
of a popup menu is calculated, it can expand
above or below, depending on the position
of the parent menu, the item being expanded
and the size of the submenu and screen resolution.

If the menu decides to expand above,
the position calculation in JMenu.getPopupMenuOrigin
may yield a coordinate above the current screen.
Later, JPopupMenu.adjustPopupLocationToFitScreen
tries to fit the entire menu into the screen.
However, it has no idea which screen is correct,
as all it has is an (x, y) location. If that
location is invalid, it may correct it by
fitting it into the screen. However, if it is
valid, but located on an incorrect screen,
then the whole logic goes awry and the menu
is fitted into the wrong screen.

Fix by pre-adjusting the Y location to fit
into the correct screen in JMenu.getPopupMenuOrigin,
where the correct screen is still known.
The resulting location may still not be final,
as the menu's height needs to be taken into
account as well, but that's exactly what
JPopupMenu.adjustPopupLocationToFitScreen does.
Since the coordinate is on the correct screen now,
it fits the menu into the same screen, which
guarantees it'll be the correct one.
diff --git a/src/java.desktop/share/classes/javax/swing/JMenu.java b/src/java.desktop/share/classes/javax/swing/JMenu.java
index bc23314..6311def 100644
--- a/src/java.desktop/share/classes/javax/swing/JMenu.java
+++ b/src/java.desktop/share/classes/javax/swing/JMenu.java
@@ -478,6 +478,16 @@
                 y = 0 - yOffset - pmSize.height;   // Otherwise drop 'up'
             }
         }
+        // Note that the y position may be later adjusted to fit the menu into the screen if possible.
+        // However, the code that does it (JPopupMenu.adjustPopupLocationToFitScreen) has no idea which screen
+        // to fit into, and determines it by the position calculated here, so we need to make sure it's on
+        // the correct screen, otherwise the menu may appear on the wrong screen (JDK-6415065).
+        if (position.y + y < screenBounds.y) { // Above the current screen?
+            y = screenBounds.y - position.y; // Fit into the screen, relative to our origin.
+        }
+        if (position.y + y >= screenBounds.y + screenBounds.height) { // Below the current screen?
+            y = screenBounds.y + screenBounds.height - 1 - position.y; // Fit into the screen, relative to our origin.
+        }
         return new Point(x,y);
     }