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



我正在尝试如何在屏幕上显示加载栏时在一个函数中处理某些数据。例如,我将一堆值添加到一个数组中 - 一个过程在我的计算机上大约需要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";
}

,但我只有一个灰色屏幕(表明背景(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((工作,这取决于负载的复杂性(((我实际上是在尝试工作的一个在我的项目中,有250多行的打开和未压缩文件,处理jsonarrays和ArrayLists等线路等。所以无论如何是否可以从函数内部更新屏幕?

事先感谢您的所有帮助:(

当您发现时,在draw()函数完成之前,处理实际上不会更新屏幕。因此,正在发生的是draw()函数是通过处理调用的,在该框架内,您恰好是自己调用draw()函数。但是,尚未完成对draw()的第一次调用,因此屏幕尚未更新。仅在完成draw()的所有呼叫时才更新,并且第一个呼叫(处理了(完成。

像这样称呼draw()通常是一个很糟糕的主意。通常,您应该使用随着时间更新的变量来更改显示每个帧的内容。

另一个选项是使用单独的线程加载文件,这样的方式可以继续。

最新更新