Search code examples
javaswingjframetransparency

How to get transparent JFrame?


When I try to run to get transparent frame it shows exception.

My code is:

public class NewJFrame extends javax.swing.JFrame {
    public NewJFrame() {
        initComponents();
        com.sun.awt.AWTUtilities.setWindowOpacity(this, 0.05f);
    }

Exception is:

Exception in thread "AWT-EventQueue-0" java.awt.IllegalComponentStateException: The frame is decorated
at java.awt.Frame.setOpacity(Frame.java:960)
at java.awt.Window$1.setOpacity(Window.java:4032)
at com.sun.awt.AWTUtilities.setWindowOpacity(AWTUtilities.java:174)
at test.NewJFrame.<init>(NewJFrame.java:28)
at test.NewJFrame$2.run(NewJFrame.java:115)

Solution

  • Call setUndecorated(true) before you call setWindowOpacity.

    In Java 7+ this support is provided in the core API (without the need to use a com.sun.* library). See How to Create Translucent and Shaped Windows for more details. For example, you could use JFrame#setOpacity instead...

    this.setOpacity(0.05f);
    

    Oh, and despite what the tutorial might suggest, I believe the only way to make a decorated window transparent is when the window is NOT using the OS provided decorations (and is using the look and feel provided decorations, which not all look and feels support), but I could be wrong