Java Reference
In-Depth Information
19
20
// long-running code to be run in a worker thread
21
public Long doInBackground()
22
{
23
return nthFib = fibonacci(n);
24
}
25
26
// code to run on the event dispatch thread when doInBackground returns
27
protected void done()
28
{
29
try
30
{
31
// get the result of doInBackground and display it
resultJLabel.setText(get().toString());
32
33
}
34
catch (InterruptedException ex)
35
{
36
resultJLabel.setText( "Interrupted while waiting for results." );
37
}
38
catch (ExecutionException ex)
39
{
40
resultJLabel.setText(
41
"Error encountered while performing calculation." );
42
}
43
}
44
45
// recursive method fibonacci; calculates nth Fibonacci number
46
public long fibonacci( long number)
47
{
48
if (number == 0 || number == 1 )
49
return number;
50
else
51
return fibonacci(number - 1 ) + fibonacci(number - 2 );
52
}
53
} // end class BackgroundCalculator
Fig. 23.24 | SwingWorker subclass for calculating Fibonacci numbers in a background thread.
(Part 2 of 2.)
SwingWorker is a generic class . In line 8, the first type parameter is Long and the second
is Object . The first type parameter indicates the type returned by the doInBackground
method; the second indicates the type that's passed between the publish and process
methods to handle intermediate results. Since we do not use publish and process in this
example, we simply use Object as the second type parameter. We discuss publish and
process in Section 23.11.2.
A BackgroundCalculator object can be instantiated from a class that controls a GUI.
A BackgroundCalculator maintains instance variables for an integer that represents the
Fibonacci number to be calculated and a JLabel that displays the results of the calculation
(lines 10-11). The BackgroundCalculator constructor (lines 14-18) initializes these
instance variables with the arguments that are passed to the constructor.
Search WWH ::




Custom Search