Showing posts from January, 2009

Java SwingWorker

The following is the full source-code for an application demonstrating the use of javax.swing.SwingWorker in Java 6. The application is very trivial and consists of a text area and two buttons: Start and Stop. When the user clicks on the Start button, the text area begins to count seconds by printing each second on a new line. This continues indefinitely until the user clicks the Stop button.

A SwingWorker is required to separate the grunt logic (in this case the infinite loop with the one-second sleep interval) from the UI logic (printing the counter in the text area and processing the user Stop button click).

The code below demonstrates the use of SwingWorker and the doInBackground(), publish(), process() and done() methods. There are other ways to achieve this same result, and the SwingWorker has additional methods that are not used here, such as the timeout enabled get() method and the progress() methods. These can come very handy in different scenarios, so please refer to the API a…

Thread that Thing!

One of my pet hates with graphical desktop programs is when developers use a single-threading model to mix UI-update-logic with grunt-logic. I see this a lot in small freeware utility programs, which is somewhat understandable (but not really). More worryingly though, I see it in large commercial products like Internet Explorer and Lotus Notes, which is most definitely unacceptable!

Problem Synopsis: A graphical desktop application can be broken down into two distinct modules: the interface module and the grunt module. The interface module is responsible for drawing the graphical interface through which the user can provide input via mouse/keyboard events and for showing visual feedback based on these events or events triggered from the grunt module. The grunt module is responsible for performing the actual grunt work required to implement the overall application’s functionality (the low-level stuff like sending/receiving bytes through sockets to display a web page in a browser, or sca…