简体   繁体   中英

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)

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

As an alternative; JavaFX supports transparent windows natively (See for example this tutorial ). If you are just starting with Java GUI programming and have no compelling reason for the use of Swing (ie. a legacy app) I recommend switching to JavaFX. Swing is in maintenance mode and all the new stuff is going into JavaFX. I doubt Swing will ever receive a single new feature from Oracle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM