JLayeredPane上的透明JLabel

时间:2012-05-12 09:13:03

标签: swing png jlabel bufferedimage jlayeredpane

我试图在JLayeredPane上显示多个重叠的PNG图像。

以下是生成包含图像的JLabel并将其添加到JLayeredPane的当前代码:

BufferedImage im = ImageIO.read(new File(fname));
JLabel uLabel = createLabelForImage(im);
mapLayeredPane.add(uLabel, new Integer(zIndex++), 1);

createLabelForImage()方法:

protected JLabel createLabelForImage(BufferedImage im) {
    JLabel label = new JLabel(new ImageIcon(im));
    label.setVerticalAlignment(JLabel.TOP);
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setOpaque(true);
    label.setBounds(0, 0, im.getWidth(), im.getHeight());

    return label;
}

我得到的是物体正确重叠,但PNG图像的透明背景被一种白灰色替换。

ImageIcon有问题吗?使用JLayeredPane?也许我必须设置像label.setBakground(sort_of_transparency_code)之类的东西?

提前致谢:)

1 个答案:

答案 0 :(得分:2)

如果您想透视,您的标签不应该是不透明的,请参阅JComponent.setOpaque

 If true the component paints every pixel within its bounds. 
 Otherwise, the component may not paint some or all of its
 pixels, allowing the underlying pixels to show through.