I am using a GUI for a program, it is not that complicated. I have a JFrame with a JPanel as it's sole component. There are various components mounted on the JPanel.
The problem comes when I try to DO something. When I click a JButton, a JTextfield is supposed to change from its current value to "Working..." WHILE the task is being performed. Unfortunately, it only changes the value AFTER the action is done and there is "idle time". The code below gives a short example.
Before the following code runs, there is a window open with a textfield with any value in it. Then a JButton is clicked and the code is in the actionlistener.
And here is what happens: "hello" is printed out nothing happens for 5 seconds THEN the GUI is updated and the textfield is changed to "Working...", which rather defeats the purpose of having it there in the first place.
What I found interesting is that hello would print out, but the GUI would not update. Which component do I need to update (the frame or the panel)? How? Where?
the Event Dispatch Thread (EDT) handles the painting, so when you do a 'long task', the EDT is blocked until the long task is finished.
you need to do your long task in a thread of its own, separate from the EDT
here's a simple demo of your problem (blocking the EDT)
here's the same code, with its own thread, and working correctly (note the SwingUtilities.invokeLater(), which updates the textfield in the EDT)
Joined: Jan 24, 2005
Thanks, that was EXACTLY what I was looking for. I had no idea you could use new threads at all, much less for what I needed. Since I'm now learning about threads (per the last post) I was wondering what the major applications are of multi-threaded programs. How and where (in general) could I use them to speed up programs?
What do you use threads for? Easy. Anything where you do two things simultaneously. I am doing several things simultaneously, eg sitting here, reading the screen, drinking my coffee. My computer is doing several things, eg displaying my reply, checking for e-mails, checking for viruses in what comes in and out, etc.
Look here in the Java tutorial. Look at the Threads forum on this website. Find any large Java book; threads represent an essential part of any non-basic Java programming.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
subject: How to make JFrame/JPanel update BEFORE idle time