JFrame frozen while updating data from streams?
Hello! I'm currently learning java as my first real language :)
While learning to work with network streams, I ran into an unrelated problem. I wrote a simple program that pulls data down from a website and displays it in a couple of fields. I set up a JLabel to display the program's status throughout the course of the update, but the window just freezes for 2-3 seconds while the update takes place.
Code:
try {
url = new URL("http://download.finance.yahoo.com/d/quotes.csv?s=" + symbol + "&f=sl1d1t1c1ohgv&e=.csv");
urlConn = url.openConnection();
* lblStatus.setText("Downloading Data");
inStream = new InputStreamReader(urlConn.getInputStream());
buff = new BufferedReader(inStream);
String csvString = buff.readLine();
StringTokenizer tokenizer = new StringTokenizer(csvString, ",");
* lblStatus.setText("Parsing");
txtpnSymbol.setText(tokenizer.nextToken().replaceAll("\"", ""));
txtpnPrice.setText(tokenizer.nextToken());
...
The label field never updates, even when the update takes several seconds. For all intensive purposes, the window is frozen. I haven't covered multithreading yet, but is this because I need to have the update and UI operating on separate threads? I'm pretty stumped.
Re: JFrame frozen while updating data from streams?
Time to "cover" multithreading I think, because that's the cause of your current problem. Your streaming is stomping on the Swing event thread (or EDT for Event Dispatch Thread), preventing it from doing its actions. Since the EDT is responsible for drawing all Swing graphics, including those of the GUI components, and all Swing user interactions, your application becomes effectively frozen if the EDT is bogged down with some long running task. The solution is to do the task in a background thread, and then updating the GUI on the event thread when necessary.
Hang on a sec. Let me look up a link for you for the tutorial...
Here it is. Please have a look at "Lesson: Concurrency in Swing". Then please come on back if you're still stuck.
Re: JFrame frozen while updating data from streams?
Thank you, that is exactly the information I was looking for. That explains why the book I've been using as a reference uses the console instead of swing elements to show status updates with streams, because all of the programs I've written so far have been single-threaded. I'll have to make learning to multithread my next goal.