How to make java.awt.Label background transparent?

删除回忆录丶 提交于 2019-12-10 11:25:03

问题


I used to do the transparent background with javax.swing.JLabel this way:

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?

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

回答1:


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.

Why not just use that existing class for your splash functionality?


As mentioned by camickr, see How to Create a Splash Screen for an example.

Now that's what 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.

For an example of using the TextLayout class, see trashgod's answer to 'Java2D Graphics anti-aliased'.




回答2:


I used to do the transparent background with javax.swing.JLabel this way:

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 Transparency to understand how tranparency works with 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.



来源:https://stackoverflow.com/questions/6399600/how-to-make-java-awt-label-background-transparent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!