如何使java.awt.Label背景透明?

时间:2011-06-18 23:42:44

标签: java label transparency awt transparent

我过去常常用javax.swing.JLabel做透明背景:

lbl.setBackground(new Color(0, 0, 0, 0));

但它不适用于java.awt.Label。有没有简单的方法使标签透明?

更新

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

}

lbl= new Label();
lbl.setBackground(new Color(0, 0, 0, 0));
splashBackground = new SplashBackground();
splashBackground.add(appNameLabel, null);

2 个答案:

答案 0 :(得分:6)

我可以看到为什么你不想加载Swing,因为它是为了引起轰动。 Sun / Oracle自己的SplashScreen实现是AWT。

为什么不直接使用现有的类来实现启动功能?


正如camickr所述,请参阅How to Create a Splash Screen以获取示例。

Splash using SplashScreen

现在那是我在说什么。


关于标签,请将它们留下。使用FontMetrics或(更好)TextLayout来确定文字的大小/位置,然后直接将其绘制到Image

有关使用TextLayout类的示例,请参阅trashgod's answer到'Java2D Graphics anti-aliased'。

答案 1 :(得分:-1)

  

我过去常常用javax.swing.JLabel做透明背景:

     

lbl.setBackground(new Color(0,0,0,0));.

这没有做任何事情。默认情况下,JLabel是透明的(即setOpaque(false))。您可能需要阅读Background With Transparency以了解透明度如何与Swing一起使用。

我从来没有使用过Label,但如果它的工作方式类似于JLabel,那么我猜你会覆盖isOpaque()方法返回false。