Panel可以实现ImageObserver接口,所以Panel类后添加“implements ImageObserver”,在Panel的构造方法中初始化Buffer Image对象,然后在Paint语句中添加Graphics的DrawImage方法,其Observer参数为this。
实例如下:
class MyPanel extends JPanel implements MouseListener, ImageObserver {
BufferedImage bi;
private static final long serialVersionUID = 1L;
public MyPanel() {
this.addMouseListener(this);
bi = new BufferedImage(600, 400, 1);
}
public void paint(Graphics graphics) {
super.paint(graphics);
Graphics g2d = (Graphics2D) graphics;
g2d.drawImage(bi, 100, 100, this);
}
}
不过此图像为空,仅显示背景色为黑色的方块。