How can i make a JPopupMenu transparent?

后端 未结 4 1394
暖寄归人
暖寄归人 2021-01-18 20:19

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

4条回答
  •  时光说笑
    2021-01-18 20:35

    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.

    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!

提交回复
热议问题