如何让JPopupMenu透明化? [英] How can i make a JPopupMenu transparent?

查看:280
本文介绍了如何让JPopupMenu透明化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想自定义 JPopupMenu 的外观,所以我在i上创建了一个自定义类,扩展了JPopupMenu类,覆盖了 paintComponent 我会为我需要定制的任何组件做的方法。

I'd like to customize the look of JPopupMenu so i made a custom class extending the JPopupMenu class on i overrode the paintComponent method as i would do for any component i need to customize.

public class CustomPopupMenu extends JPopupMenu {

    @Override
    public paintComponent(Graphics g) {
        //custom draw
    }
}

我唯一知道的问题是我无法使 JPopupMenu 透明。我虽然 setOpaque(false)就够了,我错了。

The only problem i have right know is that i'm not able to make the JPopupMenu transparent. I though setOpaque(false) would be enough, i was wrong.

我怎样才能做出 JPopupMenu 透明吗?

How can i make a JPopupMenu transparent?

推荐答案

弹出菜单的问题在于可能会实现作为顶级容器(Window),窗口是不透明的,无论你使用setOpaque()设置什么值,它都是不透明的。但是窗户也可以是半透明的。

The problem with a popup menu is that it may be realized as a top-level container (Window), and a window is opaque, no matter what value you set with setOpaque(), its opaque. But windows can be made translucent, too.

你可以通过强制使用重量级弹出窗口并残酷地改变其不透明度来破解它。试试这个作为实验的起始基础(Java7):

You can hack it by forcing the use of a heavyweight popup and brutally altering its opacity. Try this as a starting base for experiments (Java7):

import java.awt.Window;

import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;

public class TranslucentPopup extends JPopupMenu {

    {
        // need to disable that to work
        setLightWeightPopupEnabled(false);
    }

    @Override
    public void setVisible(boolean visible) {
        if (visible == isVisible())
            return;
        super.setVisible(visible);
        if (visible) {
            // attempt to set tranparency
            try {
                Window w = SwingUtilities.getWindowAncestor(this);
                w.setOpacity(0.667F);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}

请注意,使子菜单半透明!

Note that it will not make submenus translucent!

这篇关于如何让JPopupMenu透明化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆