为什么Processing (Java)中的这个静态属性会引发错误



这是我的类在处理…

class Stripe {
  PShape s;
  float x, y, w;
  static Stripe lastStripe;

  Stripe() {
    x = width / 2;
    y = 0;
    w = 150;
    s = createShape();
    s.beginShape();
    s.fill(0);
    s.noStroke();
    s.vertex(w, 0);
    s.bezierVertex(w + 50, height * 1/4, w - 50 , height * 1/3, w, height); 
    s.vertex(0, height);
    s.bezierVertex(-50, height * 1/3, 50 , height * 1/4, 0, 0); 
    //s.vertex(0, 0);

    //s.bezierVertex(50, 50, 50, 50, 100, 100); 
    s.endShape(CLOSE);
  }
  void draw() {
    pushMatrix();
    translate(x, y);
    shape(s);
    popMatrix();
  }
  void move() {
    x = x + STRIPE_VEL;
    if (x > (width + OFFSCREEN_BUFFER)) {
      x =  Stripe.lastStripe.x - STRIPE_SPACING;
      Stripe.lastStripe = this;
    }
  }
}

当我尝试编译时,我得到以下错误…

字段lastStripe只能声明为static;静态字段只能在静态或顶级类型

中声明。

看看这个Java教程,这似乎是一个有效的Java模式。虽然上面的代码是自引用的,但如果类型更改为int或类似的类型,它仍然会引发相同的错误。

这里有什么问题?

编辑:根据要求,这里是在另一个标签的草图的其余部分。我开始认为,处理的方式是只是声明这些变量作为一个"全局",而不是一个静态变量在一个类…我可能会这么做。

float STRIPE_VEL = 0.5;
float OFFSCREEN_BUFFER = 500;
float STRIPE_SPACING = 50;
int numStripes = 0;
Stripe[] stripes;

void setup() {
  float offset = 0;
  size(800, 600, P2D);
  smooth();
  numStripes = (width + 2 * OFFSCREEN_BUFFER) / STRIPE_SPACING;
  stripes = new Stripe[numStripes];
  for (int i=0; i < numStripes; i++) {
    stripes[i] = new Stripe();
    stripes[i].x = offset;
    offset = offset + inc;
  }
  Stripe.lastStripe = stripes[0];
}

void draw() {
  background(255);
  for (int i=0; i < numStripes; i++) {
    stripes[i].draw();
    stripes[i].move();
  }
  //blurAll();

}

尝试将特定文件重命名为Stripe。pde到Stripe.java。你的评论是对的:"编译过程将其嵌入到另一个类中",实际上,处理草图中的所有选项卡都围绕着一个大的java(顶级)类…因此,将其中一个重命名为.java将迫使它成为一个顶级类!

将内部类Stripe声明为static(内部)类:

static class Stripe {
  ...
}

这将确保Stripe不需要每个Stripe实例的封闭类的实例,并且您将能够创建类变量(静态字段)。


作为旁注,如果实际上不需要封闭类的实例,那么创建一个内部类static总是一个更好的做法。

最新更新