I have this weird error with my popup menu. This happens rarely and, it would seem, randomly. The problem is that when I have a submenu in my JPopupMenu - when I select a submenu, the main menu disappears and the submenu is colored incorrectly (it is similar to how the main menu buffer is colored in a submenu). I can still navigate it using the keyboard.
Here are some screenshots: Here is how it should look like

And here is what the error looks like:

Thus, the glitch in the second image is where the submenu should have been.
What could be the reason for this? There are no exceptions, this does not look like a platform, so I have no idea how to narrow it down. Please, help.
sscce, :
import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class Test {
private static Popup popup;
public static void main(String[] args) {
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
showMenu(e);
}
@Override
public void mouseReleased(MouseEvent e) {
showMenu(e);
}
private void showMenu(final MouseEvent e) {
if (e.isPopupTrigger()) {
JPopupMenu menu = new JPopupMenu();
JMenu subMenu = new JMenu("SubMenu");
menu.add(subMenu);
subMenu.add("Item 1");
subMenu.add("Item 2").addMouseMotionListener(new MouseAdapter() {
@Override
public void mouseMoved(MouseEvent e) {
hidePopup();
hidePopup();
showPopup(e, frame);
}
});
subMenu.add("Item 3");
menu.show(frame.getContentPane(), e.getX(), e.getY());
}
}
private void showPopup(MouseEvent e, JFrame frame) {
PopupFactory popupFactory = PopupFactory.getSharedInstance();
JToolTip toolTip = new JToolTip();
toolTip.setTipText("wfkwdlpfhd ");
popup = popupFactory.getPopup(frame, toolTip, e.getXOnScreen(), e.getYOnScreen());
popup.show();
}
private void hidePopup() {
if (popup != null)
popup.hide();
}
});
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}