处理 3 - 从函数调用 draw() 不会更新屏幕

Processing 3 - Calling draw() from a function doesn't update the screen

我正在试验如何在屏幕上显示加载条的同时在一个函数中处理一些数据。例如,我正在向一个数组中添加一堆值——这个过程在我的计算机上大约需要 5 秒。我有以下代码:

ArrayList<String> strs = new ArrayList<String>();
String state;
float counter;

void setup() {
  size(640, 480);
  state = "load";
  noStroke();
}

void draw() {
  if (state.equals("load")) {
    load();
  } else if (state.equals("loading")) {
    background(255);
    fill(255, 0, 0);
    rect(0, height/2-25, map(counter, 0, 10000000, 0, width), 50);
  } else if (state.equals("play")) {
    background(0, 255, 0);
  }
}

void load() {
  state = "loading";
  for (int i = 0; i < 10000000; i++) {
    strs.add(str(pow(i, 2)));

    if (i % 1000 == 0) {
      counter = i;
      draw();
    }
  }
  state = "play";
}

但是我只得到一个灰色屏幕(表明 background(255) 从未被调用过)大约 5 秒,直到我得到一个绿色屏幕。当然,我可以用类似的东西替换代码:

ArrayList<String> strs = new ArrayList<String>();
String state;
int counter;

void setup() {
  size(640, 480);
  state = "load";
  noStroke();
  counter = 0;
}

void draw() {
  if (state.equals("load")) {
    float theMillis = millis();
    while (millis()-theMillis < 1000.0/frameRate && counter < 10000000) {
      strs.add(str(pow(counter, 2)));
      counter++;
    }
    if (counter >= 10000000) {
      state = "play";
    }

    background(255);
    fill(255, 0, 0);
    rect(0, height/2-25, map(counter, 0, 10000000, 0, width), 50);
  } else if (state.equals("play")) {
    background(0, 255, 0);
  }
}

这对于这个简单的例子是有效的,但我试图让 draw() 在从函数明确调用时工作,这取决于 load() 的复杂性(我实际上试图得到的)在我的项目中工作是 250 多行长的打开和解压缩文件,处理 JSONArrays 和 ArrayLists 等)在 draw() 中将加载函数拆分成块可能是一场噩梦。那么有没有办法从函数内部更新屏幕?

在此先感谢您的帮助:)

如您所见,在 draw() 函数完成之前,Processing 不会真正更新屏幕。所以发生的事情是 draw() 函数被 Processing 调用,并且在该框架内,您碰巧自己调用了 draw() 函数。但是第一次调用 draw() 还没有完成,所以屏幕没有更新。只有当您对 draw() 的所有调用都已完成,并且第一个调用(Processing 进行的)完成时,它才会更新。

像这样给自己打电话 draw() 通常是个很糟糕的主意。您通常应该使用随时间更新的变量来更改每一帧显示的内容。

另一种选择是使用单独的线程来加载您的文件,这样绘图线程就可以继续。