java - 需要使用 'this' 的帮助 - 无法在静态上下文中使用

标签 java this affinetransform

我知道必须调用静态方法,但非静态方法必须创建一个实例。我正在尝试制作一个简单的 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/

相关文章:

javascript - 在 memoize 的 js 实现中使用 apply 时, 'this' 是什么?

Java简单绕点旋转

javax.ejb.EJBException : java. rmi.MarshalException

java - 将 Connection 类型转换为 OracleConnection 与 connection.unwrap(OracleConnection.class) 有何不同

javascript - 如何通过属性的 onclick 方法引用 javascript 对象?

java - 在 AffineTransform.rotate() 之后检索 BufferedImage 边界的新宽度和高度

selection - 在 JavaFX 中绘制变换独立布局边界

java - 关于 "conditional"方法的返回样式是否存在一般性争论?

java - 如何使用 JWNL(Wordnet 库)以估计的频率顺序查找同义词?

c++ - 将对象的 'this'指针更改为指向不同的对象