Swing/Thread ShortCut - Bad Style or Good Idea?
I tend to have trouble remembering little things and have to keep looking
them up, especially when they involve things like repeated symbols, like
creating a new thread and remembering to keep the {} () groupings straight
(it's actually part of a learning disability).
One thing that gets to me about Swing is that if a component triggers more
of an action than just setting a variable, the UI won't update until it's
done unless I use separate threads. When I write a panel for a GUI, I tend
to dispatch all the functions from within that panel with only one
actionPerformed() method. That means I have a lot of IF statements in that
one method.
It's occurred to me that if I have 8 components on a panel and 3-5 of them
trigger lengthy actions, I might as well just do something like this:
public void actionPerformed(ActionEvent aEvent) {
new Thread(
new Runnable() {
public void run() {
//eventSource is defined in the class, but not in the method
eventSource = aEvent.getSource();
if (eventSource == jButton1) {
//do stuff
}
if (eventSource == jButton2) {
//do stuff
}
...
}
}
).start();
return;
}
In other words, just start a new thread in the actionPerformed() method so
anything done will be in a separate thread so the event dispatching thread
will be able to update the UI no matter what.
Is this a good shortcut or a bad idea because of other consequences that I
may not be aware of? Is it something that could be done depending on what
the other methods it calls do?
Thanks for any comments. I'm trying to understand Swing and threads, which
I've had trouble with along the way.
Hal