Opaque components on transparent Java windows

前端 未结 1 1943
鱼传尺愫
鱼传尺愫 2021-01-25 02:11

I\'ve been successful in making java windows transparent, but I\'m having trouble superimposing opaque components on top of those windows. JFrame.setOpacity(0) and AWTUtilities

相关标签:
1条回答
  • 2021-01-25 02:49

    Using AWTUtilties.setOpaque(Window, boolean), you can get what you want. Here is an example of a half-transparent label (with a red background):

    import java.awt.Color;
    
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    
    import com.sun.awt.AWTUtilities;
    
    public class Test3 {
    
        protected static void initUI() {
            JFrame frame = new JFrame("test");
            JLabel label = new JLabel("Label text");
            label.setOpaque(true);
            label.setBackground(new Color(255, 0, 0, 128));
            frame.setUndecorated(true);
    
            AWTUtilities.setWindowOpaque(frame, false);
            frame.add(label);
            frame.pack();
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    initUI();
                }
            });
        }
    }
    

    Here are some screenshots with different values for the alpha chanel (made on a white background):

    Alpha set to 128 (half-transparent):

    Half-transparent label

    Alpha set to 0 (completely transparent):

    Completely transparent label

    Alpha set to 255 (completely opaque):

    Completely opaque

    0 讨论(0)
提交回复
热议问题