Swing Worker Thread

In the world of graphical user interfaces, responsiveness is key. Users expect applications to be smooth and interactive, even when dealing with time-consuming tasks. Swing Worker threads come to the rescue by providing a solution to execute lengthy operations in the background without freezing the user interface.

Swing Worker is a class in the Java Swing framework that helps developers manage concurrency and keep the user interface responsive during tasks that might take some time to complete. It’s especially useful when performing tasks like file I/O, network requests, or complex computations.

Following is a simple example to illustrate how Swing Worker threads can be employed to maintain a responsive UI while performing a time-consuming task:

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import javax.swing.SwingWorker;

public class SwingWorkerDemo extends JFrame {
	private JTextArea textArea;
	private JButton startButton;

	public SwingWorkerDemo() {
		setTitle("Swing Worker Demo");
		setSize(400, 300);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setLocationRelativeTo(null);

		textArea = new JTextArea();
		textArea.setEditable(false);

		startButton = new JButton("Start Lengthy Task");
		startButton.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				startButton.setEnabled(false); // Disable button during task
				textArea.setText("Task in progress...");

				// Swing Worker to simulate a lengthy task
				SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>() {
					@Override
					protected Void doInBackground() throws Exception {
						// Simulate a time-consuming operation
						Thread.sleep(3000);
						return null;
					}

					@Override
					protected void done() {
						textArea.setText("Task completed!");
						startButton.setEnabled(true); // Re-enable button
					}
				};

				worker.execute(); // Start the Swing Worker
			}
		});

		add(textArea, BorderLayout.CENTER);
		add(startButton, BorderLayout.SOUTH);
	}

	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				new SwingWorkerDemo().setVisible(true);
			}
		});
	}
}

In the example above, a Swing Worker is used to simulate a time-consuming task (sleeping for 3 seconds). While the task is running, the UI remains responsive, and the user can still interact with the application. Once the task is completed, the UI is updated to reflect the status.

Let’s see an output:

Swing Worker Thread Swing Worker Demo
Sharing Is Caring: