Help with updating thread when key is pressed
in
Programming Questions
•
9 months ago
Hi all, after looking through the examples for Threads (and some really confusing Java examples), I can't seem to figure out how to load external data in a thread when a key is pressed
. There must be a way to only download data when a key is pressed (as opposed to automatically in set intervals with sleep). Second, I'd like to be able to be updated on that process in the sketch window.
Here's what I have so far - it does load data but I don't see the "loading" text at all.
Here's what I have so far - it does load data but I don't see the "loading" text at all.
- DownloadHTML html;
- boolean getData = false;
- String[] data;
- String displayText = "";
- void setup() {
- size(900, 600);
- smooth();
- html = new DownloadHTML();
- html.start();
- }
- void draw() {
- if (getData) {
- if (html.available()) {
- data = html.getData();
- displayText = "";
- for (String s : data) {
- displayText += s + "\n";
- }
- }
- else {
- displayText = "Loading...";
- }
- getData = false;
- }
- background(255);
- fill(0);
- text(displayText, 100, 100);
- }
- void keyReleased() {
- if (key == 32) {
- getData = true;
- }
- }
- class DownloadHTML extends Thread {
- boolean running;
- boolean available;
- String[] data;
- DownloadHTML() {
- running = false;
- available = false;
- }
- boolean available() {
- return available;
- }
- String[] getData() {
- available = false;
- return data;
- }
- void start() {
- running = true;
- super.start();
- }
- void run() {
- while (running) {
- data = loadStrings("http://www.google.com");
- available = true;
- try {
- sleep ((long)(1000));
- }
- catch (Exception e) {
- }
- }
- }
- void quit() {
- running = false;
- interrupt();
- }
- }
Thanks!
1