[英]transparent parts of GIF/PNG image shown in black inside a JLabel java
I have an image (gif or png) with some transparents parts which appear in black when put inside a JLabel. 我有一个图像(gif或png),其中有一些透明的部分,当放入JLabel时会显示为黑色。
ClassLoader cl = this.getClass().getClassLoader();
ImageIcon img = new ImageIcon(cl.getResource("resources/myPicture.png"));
label = new JLabel(img);
How do I work around this problem ? 我该如何解决这个问题?
I do not need the JLabel, maybe there is a better way to display the image correctly (ie with the transparency) directly on a JPanel ? 我不需要JLabel,也许有更好的方法可以直接在JPanel上正确显示图像(即透明度)?
Thanks David 谢谢大卫
Found the culprit ! 找到了罪魁祸首!
Actually the picture is getting rescaled before being added to the JLabel and for that, I used BufferedImage.TYPE_INT_RGB instead of BufferedImage.TYPE_INT_ARGB 实际上图片在被添加到JLabel之前被重新调整,为此,我使用BufferedImage.TYPE_INT_RGB而不是BufferedImage.TYPE_INT_ARGB
I really didn't think that the rescaling method could alter this (silly me!), that's why I didn't show it in the code I added to the question... 我真的不认为重新缩放方法可以改变这个(愚蠢的我!),这就是为什么我没有在我添加到问题的代码中显示它...
David 大卫
Again, are you sure that it's the JLabel's fault? 再次,你确定这是JLabel的错吗? When I tried to do a proof of concept program, everything worked fine -- the background JPanel's pink color was seen.
当我尝试做一个概念验证程序时,一切都运行良好 - 背景是JPanel的粉红色。 eg,
例如,
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://duke.kenai.com/Oracle/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();
}
});
}
}
You may wish to create a similar program yourself to see if and where your problem is, and then post it here. 您可能希望自己创建一个类似的程序,以查看问题是否存在以及在何处,然后在此处发布。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.