我的弹出菜单有这个奇怪的错误。它很少发生,而且看似随机。问题是当我的 JPopupMenu 中有一个子菜单时 - 当我选择子菜单时,主菜单消失并且子菜单被错误地绘制(就像主菜单的缓冲区被绘制在子菜单上)。我仍然可以使用键盘导航它。
这是一些屏幕截图:这就是它的样子
这就是出现错误时的样子:
所以第二张图片上的故障是子菜单应该在的地方。
什么可能导致这种情况?没有抛出异常,它似乎与平台无关,所以我不知道如何缩小范围。请帮忙。
编辑下面是重现问题的 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();
// this is where I call the hide twice, in my case it was
// caused by some action or mouse listener calling it twice
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);
}
}