GIF / PNG图像的透明部分在JLabel java中以黑色显示

我有一个图像(gif或png),其中有一些透明的部分,当放入JLabel时会显示为黑色。

ClassLoader cl = this.getClass().getClassLoader(); ImageIcon img = new ImageIcon(cl.getResource("resources/myPicture.png")); label = new JLabel(img); 

我该如何解决这个问题?

我不需要JLabel,也许有更好的方法可以直接在JPanel上正确显示图像(即透明度)?

谢谢大卫

找到了罪魁祸首!

实际上图片在添加到JLabel之前已经重新调整,为此,我使用了BufferedImage.TYPE_INT_RGB而不是BufferedImage.TYPE_INT_ARGB

我真的不认为重新缩放方法可以改变这个(愚蠢的我!),这就是为什么我没有在我添加到问题的代码中显示它…

大卫

再次,你确定这是JLabel的错吗? 当我尝试做一个概念validation程序时,一切都运行正常 – 背景是JPanel的粉红色。 例如,

 import java.awt.Color; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class TransparentJLabel { private static final String IMAGE_PATH = "http://sofzh.miximages.com/java/OracleStratSmall.png"; private static void createAndShowUI() { JPanel panel = new JPanel(); panel.setBackground(Color.pink); URL imageUrl; try { imageUrl = new URL(IMAGE_PATH); BufferedImage image = ImageIO.read(imageUrl); ImageIcon icon = new ImageIcon(image); JLabel label = new JLabel(icon); panel.add(label); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } JFrame frame = new JFrame("TransparentJLabel"); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } public static void main(String[] args) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { createAndShowUI(); } }); } } 

您可能希望自己创建一个类似的程序,以查看问题是否存在以及在何处,然后在此处发布。