gpt4 book ai didi

java - 无法实例化

转载 作者:行者123 更新时间:2023-12-01 04:17:17 24 4
gpt4 key购买 nike

我一直在尝试创建一个用于我们的 java 游戏的 Sprite 。一切看起来都很正常,我的程序没有看到任何错误,但是当它运行时突然出现错误,无法实例化。有人能告诉我这是怎么回事吗?

@SuppressWarnings("unused")
public class TrueSprite
{
BufferedImage spriteSheet = ImageIO.read(new File("robin.png"));

int width = 240, height = 314, rows = 5 , columns = 5;

BufferedImage[] sprites = new BufferedImage[rows * columns];

public TrueSprite(int width, int height, int rows, int columns) throws IOException
{
this.width = width;
this.height = height;
this.rows = rows;
this.columns = columns;

for(int i = 0; i < rows; i++)
{
for(int j = 0; j < columns; j++)
{
sprites[(i * columns) + j ] = spriteSheet.getSubimage(i * width, j * height, width, height);
}
}

}

public void paint(Graphics g)
{
g.drawImage(sprites[1], 100, 100, null);
}


}

错误如下:

load: really.sprite.TrueSprite.class can't be instantiated.
java.lang.InstantiationException: really.sprite.TrueSprite
at java.lang.Class.newInstance(Unknown Source)
at sun.applet.AppletPanel.createApplet(Unknown Source)
at sun.applet.AppletPanel.runLoader(Unknown Source)
at sun.applet.AppletPanel.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)

最佳答案

首先,您没有构造函数,这对于实例化您的类至关重要。将其放入类声明中:

public TrueSprite() {
//code to run when your class is instantiated.
}

现在,这不会做任何特别的事情,但你可以用以下方式调用它:

TrueSprite sprite = new TrueSprite();

此外,你的类(class)需要清理。尝试将赋值代码放入我们刚刚构建的构造函数中,并将这些变量的声明置于其外部:

@SuppressWarnings("unused")
public class TrueSprite
{
private final int width;
private final int height;
private final int rows;
private final int cols;
private BufferedImage bigImg;
private BufferedImage[] sprites;

public TrueSprite(int width, int height, int rows, int columns) {
this.width = width;
this.height = height;
this.rows = rows;
this.cols = columns;
this.bigImg = ImageIO.read(new File("robin.png"));
this.sprites = new BufferedImage[rows * cols];

for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sprites[(i * cols) + j] = bigImg.getSubimage(j * width, i * height, width, height);
}
}
}

public void paint(Graphics g)
{
g.drawImage(sprites[1], 100, 100, null);
}
}

只需确保将四个有效参数传递到 TrueSprite 构造函数中即可正确调用它:

TrueSprite sprite = new TrueSprite(200, 500, 20, 50);

关于java - 无法实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19318075/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com