【问题标题】:Always null from BufferedImage in paintComponentPaintComponent 中的 BufferedImage 始终为空
【发布时间】:2013-05-27 17:39:11
【问题描述】:

我想使用 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 的正常宽度和高度)

有人知道为什么 null 总是在 paintComponent 方法中给出吗?

感谢您的帮助:)

【问题讨论】:

  • 我想知道您的问题是否出在未显示的代码中。也许您正在使用两个 ImagePanel 对象。
  • 同样不要调用super的paintComponents方法,而是调用它的paintComponent方法。
  • 我有 1 个私有 ImagePanel imagePanel;在 MainFrame 和构造函数中,我给出 imagePanel = new ImagePanel(null, null) 和 next after (startButton clicked) imagePanel = new ImagePanel(img1, img2)。我确定 img1 和 img2 不为空。
  • 你是对的。我用 (null, null) 添加到 JFrame 面板,然后更改它,使其不绘制。

标签: java swing jpanel bufferedimage paintcomponent


【解决方案1】:

您的评论显示了您的问题。您有两个 ImagPanel 对象,一个已显示且具有空图像,而另一个未显示且具有非空图像。

解决方案:只创建一个对象。给它一个setImages(Image img1, Image img2) 方法,当你需要设置图像时调用它。

另外根据我的评论更改你的超级方法调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-10
    • 2012-03-10
    • 2011-10-13
    • 2021-09-01
    • 2021-05-05
    • 2019-02-16
    • 2016-11-07
    • 1970-01-01
    相关资源
    最近更新 更多