我想使用 2 个图像(从文件加载后)创建 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);
}
}
}
但是当我 repaint() 这个类时,我总是从 FinalImage 中得到 null。 我使用了 deepCopy 但这个方法不会改变任何东西。 我还检查了 toString 方法给出的内容,一切都正常(它给出了 FinalImage 的正常宽度和高度)
有人知道为什么在paintComponent方法中总是给出null吗?
感谢您的帮助:)
最佳答案
你的评论说明了你的问题。您有两个 ImagPanel 对象,一个显示且包含空图像,另一个不显示且包含非空图像。
解决方案:只创建一个对象。给它一个 setImages(Image img1, Image img2)
方法,并在需要设置图像时调用它。
另外,根据我的评论,更改您的 super 方法调用。
关于java - PaintComponent 中的 BufferedImage 始终为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16778066/