I don't know how many people or any one now uses Swing for designing applications in Java. But while reading Java docs in my free time I came across this class called SwingWorker, now many of who work/had worked in Swing might be saying "Whats new in this class"!! Well, nothing is new in there but this class is new for me coz I never worked in Swing, but in my college days I was working on a project using Swing called Visual Java. A NetBeans kind of software, I stopped working on it when I came to know that its already there.. :)
Coming back to SwingWorker. I am writing this post for this class is because this class is really a handy for those who are developing or starting to develop applications using Swing. While developing any software if there is any long running task, we put it in a separate thread, Background thread. So SwingWorker provides us the same functionality adding some methods where we can put our UI manipulation code.
Both the classes provide doInBackground where you should write code for your long running task. SwingWorker provides process method where you can put your code to update application UI. It provides another method done, this method is called when your task is completed. To publish current progress of task it provides another method publish, to which you can pass the data to either process it or current progress of our task.
Following example shows how to use SwingWorker class.
Coming back to SwingWorker. I am writing this post for this class is because this class is really a handy for those who are developing or starting to develop applications using Swing. While developing any software if there is any long running task, we put it in a separate thread, Background thread. So SwingWorker provides us the same functionality adding some methods where we can put our UI manipulation code.
Both the classes provide doInBackground where you should write code for your long running task. SwingWorker provides process method where you can put your code to update application UI. It provides another method done, this method is called when your task is completed. To publish current progress of task it provides another method publish, to which you can pass the data to either process it or current progress of our task.
Following example shows how to use SwingWorker class.
class BackgroundTask extends SwingWorker<String, Integer>{ @Override protected String doInBackground() throws Exception { // add code for your long running task publish(progress); return result; } @Override protected void process(List<Integer> chunks) { super.process(chunks); // add code to update UI } @Override protected void done() { super.done(); // task completed, add code to perform some action upon it } }
Comments
Post a Comment