fiziwig wrote:
Newbie question:
I know event handlers, like button click handlers, are supposed to be
short and sweet so the GUI doesn't hang. But I need a button that
launches a long-running computation that might take a minute or two to
complete, but I don't want the GUI to hang while this number cruncher
is doing its thing. In C++ I'd just slice some time out for the process
in the Windows event dispatch loop, but you don't write your own event
dispatch loop in Java like you do in Windows so I'm clueless here.
What's the correct Java way to do that?
Thanks,
--gary
public void doAction(Action a) {
Thread longRunning = new Thread( new LongRunningComp() );
longRunning.start();
}
class LongRunnningComp implements Runnable() {
public void run() {
// do stuff that takes ages...
SwingUtilities.invokeLater( new GuiUpdater(textArea,
answerThatTookAgesToGet) );
}
}
class GuiUpdater implements Runnable() {
JTextArea textAreaToUpdate;
String longRunningCompAnswer;
public GuiUpdater(JTextArea textArea, String answer) {
textAreaToUpdate = textArea;
String longRunningCompAnswer = answer;
}
public void run() {
textAreaToUpdate .setText(longRunningCompAnswer );
}
}
Once you see how it works, then you may want to use anonymous inner
classes instead of the two helper ones.
Andrew
Thanks. I tried that approach out on your suggestion and it works
Then I also discovered: class DoLongThing extends Thread {...} etc.