Reputation: 2821
I'm experimenting with how to process some data in one function while displaying a loading bar on the screen. For an example, I'm adding a bunch of values to an array - a process that takes about 5 seconds on my computer. I have the following code:
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";
}
But I just get a grey screen (indicating that background(255) has never been called) for about 5 seconds until I get a green screen. I could, of course, replace the code with something like:
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);
}
}
And that would work for this simple example, but I am trying to get draw() to work when called from a function explicitly as depending on the complexity of load() (the one I'm actually trying to get to work in my project is 250+ lines long of opening and uncompressing files, processing JSONArrays and ArrayLists, etc.) splitting the load function into chunks inside draw() could be a nightmare. So is there anyway to update the screen from inside a function?
Thanks in advance for all your help :)
Upvotes: 0
Views: 1262
Reputation: 42176
As you're discovering, Processing does not actually update the screen until the draw()
function completes. So what's happening is the draw()
function is called by Processing, and inside that frame, you happen to be calling the draw()
function yourself. But that first call to draw()
hasn't completed yet, so the screen is not updated. It's only updated when all of your calls to draw()
are done, and the very first call (which Processing made) completes.
Calling draw()
yourself like this is usually a pretty bad idea. You should usually use a variable that you update over time to change what's displaying each frame.
Another option is to use a separate thread to load your file, that way the drawing thread can continue.
Upvotes: 1