Java Reference
In-Depth Information
Method
Description
Receives intermediate results from the publish method and processes
these results on the event dispatch thread.
process
setProgress
Sets the progress property to notify any property change listeners on the
event dispatch thread of progress bar updates.
Fig. 23.23 | Commonly used SwingWorker methods. (Part 2 of 2.)
23.11.1 Performing Computations in a Worker Thread: Fibonacci
Numbers
In the next example, the user enters a number n and the program gets the n th Fibonacci
number, which we calculate using the recursive algorithm discussed in Section 18.5. Since
the algorithm is time consuming for large values, we use a SwingWorker object to perform
the calculation in a worker thread. The GUI also provides a separate set of components
that get the next Fibonacci number in the sequence with each click of a button, beginning
with fibonacci(1). This set of components performs its short computation directly in
the event dispatch thread. This program is capable of producing up to the 92nd Fibonacci
number—subsequent values are outside the range that can be represented by a long . Recall
that you can use class BigInteger to represent arbitrarily large integer values.
Class BackgroundCalculator (Fig. 23.24) performs the recursive Fibonacci calcula-
tion in a worker thread . This class extends SwingWorker (line 8), overriding the methods
doInBackground and done . Method doInBackground (lines 21-24) computes the n th
Fibonacci number in a worker thread and returns the result. Method done (lines 27-43)
displays the result in a JLabel .
1
// Fig. 23.24: BackgroundCalculator.java
2
// SwingWorker subclass for calculating Fibonacci numbers
3
// in a background thread.
4
import javax.swing.SwingWorker;
5
import javax.swing.JLabel;
6
import java.util.concurrent.ExecutionException;
7
8
public class BackgroundCalculator extends SwingWorker<Long, Object>
9
{
10
private final int n; // Fibonacci number to calculate
11
private final JLabel resultJLabel; // JLabel to display the result
12
13
// constructor
14
public BackgroundCalculator( int n, JLabel resultJLabel)
15
{
16
this .n = n;
17
this .resultJLabel = resultJLabel;
18
}
Fig. 23.24 | SwingWorker subclass for calculating Fibonacci numbers in a background thread.
(Part 1 of 2.)
 
 
Search WWH ::




Custom Search