【问题标题】:Need help using 'this' - cannot use in a static context使用“this”需要帮助 - 不能在静态上下文中使用
【发布时间】:2013-03-08 20:07:04
【问题描述】:

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

【问题讨论】:

    标签: java this affinetransform


    【解决方案1】:

    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);
       }
    }
    

    【讨论】:

    • 那么我该如何解决呢?这是我最初的问题
    【解决方案2】:

    为了访问包含对象,为什么不将对象的实例作为参数传递给静态方法,即:

    public static void updateBuffer(Image image, int XPos , int YPos , int Height , int Width , int Rotation, AffineTransform trans, Object parent)
    

    【讨论】:

      猜你喜欢
      • 2023-04-04
      • 2013-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多