我知道必须调用静态方法,但非静态方法必须创建一个实例。我正在尝试制作一个简单的 2D 游戏。我希望所有图形都出现在一个窗口中,而不是每个类的几个不同窗口中,这就是正在发生的情况。因此,我决定使用静态 updateBackBuffer 方法创建一个paintGraphics 类,该方法会将图像添加到graphics2D 变量(名为g2d)中。我尝试了这段代码,但出现错误,无法在静态上下文中使用它,我该如何解决这个问题?:
public static void updateBuffer(Image image, int XPos , int YPos , int Height , int Width , int Rotation, AffineTransform trans) {
trans.translate(XPos,YPos);
trans.rotate(Rotation); //More lines will probably be more lines totransform the shape more as the game gets more advanced
g2d.drawImage(image,trans,this);
}
最佳答案
在行:g2d.drawImage(image,trans,this);
中,this
指的是定义updateBuffer<的类的实例
。由于 updateBuffer
被声明为 static
,因此它不能使用引用 this
,因为 this
不能保证被初始化。
更新
public class Foo {
public Foo() {
...
}
public static void updateBuffer(Image image, int XPos , int YPos , int Height , int Width , int Rotation, AffineTransform trans, Foo foo) {
trans.translate(XPos,YPos);
trans.rotate(Rotation); //More lines will probably be more lines totransform the shape more as the game gets more advanced
g2d.drawImage(image,trans,foo); // <-- 'foo' stands in for 'this'
}
public static void main(String[] args) {
Image i = new Image();
int x,y,h,w,r;
AffineTransform t = new AffineTransform();
Foo f = new Foo();
Foo.updateBuffer(i,x,y,h,w,r,t,f);
}
}
关于java - 需要使用 'this' 的帮助 - 无法在静态上下文中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15302397/