Java Reference
In-Depth Information
110
111
// main method begins program execution
112
public static void
main(String[] args)
113
{
114
FibonacciNumbers application =
new
FibonacciNumbers();
115
application.setDefaultCloseOperation(
EXIT_ON_CLOSE
);
116
}
117
}
// end class FibonacciNumbers
a) Begin calculating Fibonacci of 40 in the
background
b) Calculating other Fibonacci values while
Fibonacci of 40 continues calculating
c) Fibonacci of 40 calculation finishes
Fig. 23.25
|
Using
SwingWorker
to perform a long calculation with results displayed in a GUI.
(Part 4 of 4.)
Lines 48-77 register the event handler for the
goJButton
. If the user clicks this
JButton
, line 58 gets the value entered in the
numberJTextField
and attempts to parse it
as an integer. Lines 72-73 create a new
BackgroundCalculator
object, passing in the user-
entered value and the
fibonacciJLabel
that's used to display the calculation's results.
Line 74 calls method
execute
on the
BackgroundCalculator
, scheduling it for execution
in a separate worker thread. Method
execute
does not wait for the
BackgroundCalcu-
lator
to finish executing. It returns immediately, allowing the GUI to continue pro-
cessing other events while the computation is performed.
If the user clicks the
nextNumberJButton
in the
eventThreadJPanel
, the event handler
registered in lines 86-102 executes. Lines 92-95 add the previous two Fibonacci numbers
stored in
n1
and
n2
to determine the next number in the sequence, update
n1
and
n2
to their
new values and increment
count
. Then lines 98-99 update the GUI to display the next
number. The code for these calculations is in method
actionPerformed
, so they're per-
formed on the
event dispatch thread
. Handling such short computations in the event dis-