繁体   English   中英

透明Java窗口上的不透明组件

[英]Opaque components on transparent Java windows

我已经成功地使Java窗口透明,但是在这些窗口上叠加不透明组件时遇到了麻烦。 JFrame.setOpacity(0)和AWTUtilities setWindowOpacity都将透明性传递给组成组件。 另外,JFrame.setBackground(0,0,0,0)以某种方式使所述组件失去透明度。

我怎样才能解决这个问题?

测试类:分别是透明背景,setOpacity和AWTUtility

import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.Color;

public class test {
public static void main(String[] args){
JFrame frame = new JFrame("test");
JLabel label = new JLabel("Label text");
frame.setUndecorated(true);
frame.setBackground(new Color(0,0,0,128));
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}


public class test2 {

public static void main(String[] args){
JFrame frame = new JFrame("test");
JLabel label = new JLabel("Label text");
frame.setUndecorated(true);
frame.setOpacity(.50f);
frame.add(label);
frame.pack();
frame.setVisible(true);
}
}


import com.sun.awt.AWTUtilities;
import java.lang.reflect.Method;
import java.awt.Window;

public class test3 {
public static void main(String[] args){
JFrame frame = new JFrame("test");
JLabel label = new JLabel("Label text");
frame.setUndecorated(true);

try {
Class<?> awtUtilitiesClass = Class.forName("com.sun.awt.AWTUtilities");
Method mSetWindowOpacity = awtUtilitiesClass.getMethod("setWindowOpacity", Window.class, float.class);
mSetWindowOpacity.invoke(null, frame, Float.valueOf(0.50f));
} catch (Exception x){}     

frame.add(label);
frame.pack();
frame.setVisible(true);
}
}

编辑:我曾尝试在Windows上运行setBackground(0,0,0,0),但在Linux(xfce)上无法正常工作。

使用AWTUtilties.setOpaque(Window,boolean),可以获得所需的内容。 这是一个半透明标签(带有红色背景)的示例:

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();
            }
        });
    }
}

以下是Alpha香奈儿(在白色背景上制作)的不同值的一些屏幕截图:

Alpha设置为128(半透明):

半透明标签

Alpha设置为0(完全透明):

完全透明的标签

Alpha设置为255(完全不透明):

完全不透明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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