【发布时间】: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