Example
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
class PrimeNumbersTask extends SwingWorker<List<Integer>, Integer> {
private final int numbersToFind;
private final JTextArea textArea;
PrimeNumbersTask(JTextArea textArea, int numbersToFind) {
this.numbersToFind = numbersToFind;
this.textArea = textArea;
}
@Override
public List<Integer> doInBackground() {
final List<Integer> result = new ArrayList<>();
boolean interrupted = false;
for (int i = 0; !interrupted && (i < numbersToFind); i += 2) {
interrupted = doIntenseComputing();
result.add(i);
publish(i); // sends data to process function
}
return result;
}
private boolean doIntenseComputing() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
return false;
}
@Override
protected void process(List<Integer> chunks) {
for (int number : chunks) {
// the process method will be called on the EDT
// thus UI elementes may be updated in here
textArea.append(number + "\n");
}
}
}
public class SwingWorkerExample extends JFrame {
private JTextArea textArea;
public SwingWorkerExample() {
super("Java SwingWorker Example");
init();
}
private void init() {
setSize(400, 400);
setLayout(new GridLayout(1, 1));
textArea = new JTextArea();
add(textArea);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
System.exit(0);
}
});
}
public static void main(String args[]) throws Exception {
SwingWorkerExample ui = new SwingWorkerExample();
EventQueue.invokeLater(() -> {
ui.setVisible(true);
});
int n = 100;
PrimeNumbersTask task = new PrimeNumbersTask(ui.textArea, n);
task.execute(); // run async worker which will do long running task on a
// different thread
System.out.println(task.get());
}
}