3

我的问题与类似,但我认为有一个更简单的例子。

基本上通过调用AWTUtilities.setWindowOpaque(window, false)使 JFrame 的背景透明,我的 JPopupMenu 有时会显示为空白。

public class JavaApplication8 {

    JPopupMenu popup;
    JMenuItem open;
    JLabel bgLabel = new JLabel("testing");

    public static void main(String[] args) {
        // TODO code application logic here

        JFrame window = new JFrame("test");

        URL bgURL = JavaApplication8.class.getResource("images/bg.jpg");
        ImageIcon bg = new ImageIcon(bgURL);

        JavaApplication8 test = new JavaApplication8();
        test.setPopupMenu();
        test.bgLabel.setIcon(bg);

        window.add(test.bgLabel, BorderLayout.CENTER);

        window.setUndecorated(true);
        AWTUtilities.setWindowOpaque(window, false);        
        //window.pack();
        window.setSize(200, 200);
        window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        window.setLocationRelativeTo(null);
        window.setVisible(true);

    }

    public void setPopupMenu(){
        popup = new JPopupMenu();
        open = new JMenuItem("Test");

        popup.add(open);
        this.bgLabel.setComponentPopupMenu(popup);     
    }

}

这是正在发生的事情的图像:

在此处输入图像描述 在此处输入图像描述

有趣的是,每当我单击 JFrame 的右侧时,都会发生这种情况。不知道为什么。请记住,我不是 100% 确定这AWTUtilities.setWindowOpaque(window, false)确实是导致此问题的原因,但是每当我删除该行时,一切似乎都很好。

编辑:如前所述camickrlooks like this happens when the popup menu is not fully contained in the bounds of the parent window.

4

2 回答 2

2

背景: 我不确定为什么使用透明/半透明背景会导致重量级弹出窗口出现问题以及它们如何绘制,但它确实 - 无论您是否使用AWTUtilities.setWindowOpaque(window, false)frame.setBackground(new Color(0, 0, 0, 0)).

HeavyWeightPopup弹出窗口无法完全放入目标窗口时,将创建 s 。所以 +User2280704 如果您单击窗口的最底部,您的问题也会出现。LightWeightPopups 没有这个问题——因此,菜单在窗口中间工作。

另外,值得注意的是,通常菜单第一次会很好地呈现,而不是接下来的时间。

答: 我想出了一个解决方法,在任何弹出窗口显示后调用重绘。启动应用程序时只需调用以下代码。

PopupFactory.setSharedInstance(new PopupFactory() 
{
    @Override
    public Popup getPopup(Component owner, final Component contents, int x, int y) throws IllegalArgumentException
    {
        Popup popup = super.getPopup(owner, contents, x, y);
        SwingUtilities.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                contents.repaint();
            }
        });
        return popup;
    }
});
于 2013-08-22T19:25:59.393 回答
2

每当我单击 JFrame 的右侧时,都会发生这种情况

当弹出菜单未完全包含在父窗口的边界中时,似乎会发生这种情况。不知道如何解决这个问题。

在 Java 7 中,您可以使用:

frame.setBackground(new Color(0, 0, 0, 0));

为了透明度。

于 2013-08-16T02:58:49.370 回答