我有一个从png文件创建的BufferedImage.创建它时,我将类型设置为TYPE_INT_ARGB,这应该为我提供透明图像.当我在JPanel中使用paintComponent绘制图像时,得到的图像带有黑色背景.我真的需要使它透明,以便任何帮助将是有用的.这是为了清楚起见的代码:
public class ImagePanel extends JPanel {
private static final long serialVersionUID = 1L;
private BufferedImage image;
public ImagePanel() {
this.image = null;
}
public void createImage(String fileName) {
this.image = ImageUtilities.getBufferedImage(fileName, this);
this.repaint();
}
public void paint(Graphics g) {
g.drawImage(this.image, 0, 0, this);
}
}
这是我如何加载图像:
public class ImageUtilities {
/** Create Image from a file, then turn that into a BufferedImage.
*/
public static BufferedImage getBufferedImage(String imageFile, Component c) {
Image image = c.getToolkit().getImage(imageFile);
waitForImage(image, c);
BufferedImage bufferedImage = new BufferedImage(image.getWidth(c), image.getHeight(c),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, c);
return(bufferedImage);
}
最后要添加的是,此ImagePanel在另一面板内,如果有任何意义的话.
解决方法:
不知道这是否可以解决您的问题,但是:
>覆盖paintComponent而不是paint(http://download.oracle.com/javase/tutorial/uiswing/painting/closer.html)
>考虑使用较新的javax.imageio API
>确保面板不是不透明的(opaque = false)