Reputation: 454
My Problem:
I have a long executing task in my application (Needs to fetch data from the web), and I'm trying to display a loading screen with an animation (Just a rotating circle, no progress bar needed) while the task is being executed
What I have done so far:
I created the design for the loading screen in a panel and added it to a JFrame and tried to call instantiate the JFrame before the the code for the long process, and then dispose it after the process is done, like this:
LoadingFrame frame = new LoadingFrame();
//Long Process
Wiring wiring = new Wiring(node.source);
wiring.generateScopeForTargetNode();
// close() calls setVisible(false) and then dispose()
frame.close();
However, the frame did not get repainted until the task was done and all I received was a blank box, and in the end it didn't get disposed.
I searched SO for the problem, and found that it has to do with Threads and concurrency (Which I am unfamiliar with) and found suggestions to use JDialog
instead of JFrame
, so I followed the suggestion. What I ended up with is this:
What I need Help with:
I have tried to search more for the problem and found suggestions that I should use SwingWorker
to run one task in a thread and the animation in another if I have understood correctly. However I am unfamiliar with threads and with SwingWorker
and need help in creating a simple SwingWorker
instance that achieves what I'm trying to do
Upvotes: 2
Views: 1023
Reputation: 205855
Use a SwingWorker
"to fetch data from the web" in the background. publish()
interim results as they arrive. Your implementation of process()
can then safely update a view component's model on the event dispatch thread. With even modest granularity, the user will start seeing data instead of an uninformative animation. This complete example updates the TableModel
of a listening JTable
, but the Document
of a listening JTextComponent
would work as well.
Upvotes: 1