java总是从paintComponent中的BuffereImage为空
我想用两张图片(从文件加载后)创建FinalImage并显示它。所以我创建了一个类:
public class ImagePanel extends JPanel{
private static final long serialVersionUID = 1L;
private BufferedImage firstImage;
private BufferedImage secondImage;
private BufferedImage finalImage;
public ImagePanel(BufferedImage first, BufferedImage second){
if(first != null && second != null){
this.firstImage = deepCopy(first);
this.secondImage = deepCopy(second);
finalImage = new BufferedImage(firstImage.getWidth()*2, firstImage.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics g = finalImage.getGraphics();
g.drawImage(firstImage, 0, 0, null);
g.drawImage(secondImage, firstImage.getWidth(), 0, null);
System.out.println("FinalImage"+finalImage.toString());
}
}
private BufferedImage deepCopy(BufferedImage bi) {
ColorModel cm = bi.getColorModel();
boolean isAlphaPremultiplied = cm.isAlphaPremultiplied();
WritableRaster raster = bi.copyData(null);
return new BufferedImage(cm, raster, isAlphaPremultiplied, null);
}
protected void paintComponent(Graphics g) {
super.paintComponents(g);
if(finalImage != null){
g.drawImage(finalImage, 20, 20, null);
}
}
}
但是当我重新绘制这个类时,finalImage中的值总是为空。 我使用了deepCopy,但这种方法没有改变任何东西。 我还检查了toString方法给出了什么,并且一切都正常(它给出了最终图像的正常宽度和高度)
有人知道为什么null总是在paintComponent方法中让步吗
谢谢你的帮助:)
# 1 楼答案
你的评论说明了你的问题。有两个ImagPanel对象,一个显示并带有空图像,另一个未显示且带有非空图像
解决方案:只创建一个对象。给它一个
setImages(Image img1, Image img2)
方法,并在需要设置图像时调用它同样根据我的评论,改变你的超级方法调用