如何使 java.awt.Label 背景透明?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6399600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make java.awt.Label background transparent?
提问by bancer
I used to do the transparent background with javax.swing.JLabel this way:
我曾经用 javax.swing.JLabel 这种方式做透明背景:
lbl.setBackground(new Color(0, 0, 0, 0));
.
lbl.setBackground(new Color(0, 0, 0, 0));
.
But it doesn't work with java.awt.Label. Is there any simple way to make the label transparent?
但它不适用于 java.awt.Label。有没有什么简单的方法可以让标签透明?
Update:
更新:
public class SplashBackground extends Panel {
private static final long serialVersionUID = 1L;
private Image image = null;
/**
* This is the default constructor
*/
public SplashBackground() {
super();
initialize();
}
/**
* This method initializes this
*
*/
private void initialize() {
image = Toolkit.getDefaultToolkit().createImage(getClass().getResource("/splash/splash.jpg"));
this.setLayout(null);
}
@Override
public void paint(Graphics g) {
super.paint(g);
if(image != null) {
g.drawImage(image, 0,0,this.getWidth(),this.getHeight(),this);
}
}
}
and
和
lbl= new Label();
lbl.setBackground(new Color(0, 0, 0, 0));
splashBackground = new SplashBackground();
splashBackground.add(appNameLabel, null);
回答by Andrew Thompson
I can see why you do not want to load Swing, since it is for a splash. Sun/Oracle's own implementation of SplashScreen
is AWT all the way.
我明白你为什么不想加载 Swing,因为它是为了飞溅。Sun/Oracle 自己的实现SplashScreen
方式一直是AWT。
Why not just use that existing class for your splash functionality?
为什么不将现有的类用于您的启动功能?
As mentioned by camickr, see How to Create a Splash Screenfor an example.
正如 camickr 所提到的,请参阅如何创建启动画面作为示例。
Now that'swhat I'm talking about.
现在这就是我要说的。
As to the labels, leave them out. Use FontMetrics
or (better) TextLayout
to determine the size/position of the text, then just paint it directly to the Image
.
至于标签,将它们排除在外。使用FontMetrics
或(更好)TextLayout
来确定文本的大小/位置,然后直接将其绘制到Image
.
For an example of using the TextLayout
class, see trashgod's answerto 'Java2D Graphics anti-aliased'.
回答by camickr
I used to do the transparent background with javax.swing.JLabel this way:
lbl.setBackground(new Color(0, 0, 0, 0));.
我曾经用 javax.swing.JLabel 这种方式做透明背景:
lbl.setBackground(new Color(0, 0, 0, 0));。
That doesn't do anything. A JLabel is transparent by default (ie setOpaque(false)). You may want to read Background With Transparencyto understand how tranparency works with Swing.
那没有任何作用。JLabel 默认是透明的(即 setOpaque(false))。您可能需要阅读具有透明度的背景以了解透明度如何与 Swing 配合使用。
I've never used a Label but if it works anything like a JLabel, then I would guess you override the isOpaque() method to return false.
我从来没有使用过标签,但如果它像 JLabel 一样工作,那么我猜你会覆盖 isOpaque() 方法以返回 false。