[英]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.