Java Reference
In-Depth Information
patch thread does not cause the GUI to become unresponsive, as with the recursive
algorithm for calculating the Fibonacci of a large number. Because the longer Fibonacci
computation is performed in a separate worker thread using the SwingWorker , it's possible
to get the next Fibonacci number while the recursive computation is still in progress.
23.11.2 Processing Intermediate Results: Sieve of Eratosthenes
We've presented an example that uses the SwingWorker class to execute a long process in
a background thread and update the GUI when the process is finished. We now present an
example of updating the GUI with intermediate results before the long process completes.
Figure 23.26 presents class PrimeCalculator , which extends SwingWorker to compute
the first n prime numbers in a worker thread . In addition to the doInBackground and done
methods used in the previous example, this class uses SwingWorker methods publish ,
process and setProgress . In this example, method publish sends prime numbers to
method process as they're found, method process displays these primes in a GUI com-
ponent and method setProgress updates the progress property. We later show how to
use this property to update a JProgressBar .
1
// Fig. 23.26: PrimeCalculator.java
2
// Calculates the first n primes, displaying them as they are found.
3
import javax.swing.JTextArea;
4
import javax.swing.JLabel;
5
import javax.swing.JButton;
6
import javax.swing.SwingWorker;
7
import java.security.SecureRandom;
8
import java.util.Arrays;
9
import java.util.List;
10
import java.util.concurrent.CancellationException;
11
import java.util.concurrent.ExecutionException;
12
13
public class PrimeCalculator extends SwingWorker<Integer, Integer>
14
{
15
private static final SecureRandom generator = new SecureRandom();
16
private final JTextArea intermediateJTextArea; // displays found primes
17
private final JButton getPrimesJButton;
18
private final JButton cancelJButton;
19
private final JLabel statusJLabel; // displays status of calculation
20
private final boolean [] primes; // boolean array for finding primes
21
22
// constructor
23
public PrimeCalculator( int max, JTextArea intermediateJTextArea,
24
JLabel statusJLabel, JButton getPrimesJButton,
25
JButton cancelJButton)
26
{
27
this .intermediateJTextArea = intermediateJTextArea;
28
this .statusJLabel = statusJLabel;
29
this .getPrimesJButton = getPrimesJButton;
30
this .cancelJButton = cancelJButton;
31
primes = new boolean [max];
32
Fig. 23.26 | Calculates the first n primes, displaying them as they are found. (Part 1 of 3.)
 
Search WWH ::




Custom Search