How to get transparent JFrame?

匆匆过客 提交于 2019-12-08 09:12:33

问题


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)

回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/28656647/how-to-get-transparent-jframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!