【问题标题】:Opaque components on transparent Java windows透明 Java 窗口上的不透明组件
【发布时间】:2012-05-18 05:46:34
【问题描述】:

我已经成功地使 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) 上不能正常工作。

【问题讨论】:

  • 如需尽快获得更好的帮助,请发帖SSCCE

标签: java swing transparency


【解决方案1】:

使用 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 chanel 屏幕截图(在白色背景上制作):

Alpha 设置为 128(半透明):

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

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

【讨论】:

  • 在我的计算机上,即使我将 alpha 设置为 0,此示例的标签也是部分透明的,尽管它不应该如此。我似乎无法让任何工作,我开始认为这是因为我使用的平台。
  • @septette 我用不同的屏幕截图更新了我的帖子,并将背景颜色的 alpha 值设置为不同的值。我的配置(这里)是带有 JDK7 的 WinXP(但我很确定它适用于 JDK6,至少是最新版本)
猜你喜欢
  • 2013-02-21
  • 2012-08-04
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 2020-09-12
  • 1970-01-01
相关资源
最近更新 更多