尝试在java中绘制图像时出现奇怪的错误?

时间:2014-05-08 16:19:50

标签: java swing paintcomponent graphics2d

我正在尝试将一个函数从主类移动到我正在制作的小游戏中的子类。我已将函数从主类复制并粘贴到子类中,由于某种原因我收到此错误:

no suitable method found for drawImage(java.awt.Image,int,int,pony)
method java.awt.Graphics2D.drawImage(java.awt.BufferedImage, java.awt.BufferedImageOp, int, int) is not applicable; (actual argument java.awt.Image cannot be converted to java.awt.BufferedImage by method invocation conversion);

这是功能:

public void explode(Graphics g)
{
    Graphics2D g2d = (Graphics2D) g;

    int i=0;
    float angle = 0.03f;
    float PI = 3.14159f;
    int x2,y2;
    int r=40;

    while(r<200)
    {
        while (angle < 2 * PI)
        {
            x2 = (int)this.x + (int) (Math.cos(angle)*r);
            y2 = (int)this.y + (int) (Math.sin(angle)*r);

            g2d.drawImage(sparkles[i].getImage(), x2, y2,this);

            angle+=0.1;
            i+=1;
        }
        i=0;
        angle=0.03f;
        r+=5;
    }

}

这是主类中的函数调用:

public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;

    for(int i=0;i<curPonies;i++)
    {
       if(ponies[i].colliding())
       {
          ponies[i].explode(g);
       }
    }
}

如果我将explode函数移动到主类中它可以正常工作,但如果我尝试从另一个类调用它,我会得到上面的错误。如果有人能告诉我为什么会这样,我会非常感谢你的帮助。

非常感谢!

1 个答案:

答案 0 :(得分:1)

以这种方式打电话

g2d.drawImage(sparkles[i].getImage(), x2, y2, null); // if observer is not known

请看Graphics#drawImage(Image img,int x,int y,ImageObserver observer)

java.awt.Graphics2Djava.awt.Graphics的子类。


在您的情况下,最后一个参数this必须实施ImageObserver

g2d.drawImage(sparkles[i].getImage(), x2, y2,this);
//last argument this must be an ImageObserver