Disable Background drawing in JFrame in order to properly display Aero (DWM) effects

。_饼干妹妹 提交于 2019-12-03 02:39:23

Great question.

The most obvious answer would be

WindowUtils.setWindowOpaque(this, false);

That gives you the visual effects you want but unfortunately prevents you from being able to click on the Window!

The second thing I tried was to override the paint() method to perform the same actions that Window.paint() does when the opaque flag is set to false. That didn't do anything.

Then I tried using Reflection. Reflectively setting Window.opaque to true gave the same results as using WindowUtils.

Finally, I tried adding this to enableAeroEffect():

Method m = null;
try {
    m = Window.class.getDeclaredMethod("setLayersOpaque", Component.class, Boolean.TYPE);
    m.setAccessible(true);
    m.invoke(null, this, false);
} catch ( Exception e ) {
    //TODO: handle errors correctly
} finally {
    if ( m != null ) {
        m.setAccessible(false);
    }
}

This worked! The Window still responds properly to mouse events, but the background isn't drawn. The drawing is a bit glitchy, but should get you on your way.

Obviously it's fragile since it relies on Reflection. If I were you, I'd take a look at what Window.setLayersOpaque() does, and try to replicate that in a way that doesn't rely on Reflection.

Edit: On inspection of the setLayersOpaque method, it really seems to boil down to disabling double-buffering on the transparent components. Call this method from your enableAeroEffect() method and you're on your way:

//original source: Sun, java/awt/Window.java, setLayersOpaque(Component, boolean)
private static void setLayersTransparent(JFrame frame) {
    JRootPane root = frame.getRootPane();
    root.setOpaque(false);
    root.setDoubleBuffered(false);

    Container c = root.getContentPane();
    if (c instanceof JComponent) {
        JComponent content = (JComponent) c;
        content.setOpaque(false);
        content.setDoubleBuffered(false);
    }
    frame.setBackground(new Color(0, 0, 0, 0));
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!