Java Reference
In-Depth Information
the index to method
publish
so that it can be displayed as an
intermediate result
in the
GUI and line 64 increments the number of primes found. Lines 66-67 set all multiples of
the current index to
false
to indicate that they're not prime. When the entire array has
been traversed, line 72 returns the number of primes found.
Method
process
Lines 76-80 declare method
process
, which executes in the event dispatch thread and re-
ceives its argument
publishedVals
from method
publish
. The passing of values between
publish
in the worker thread and
process
in the event dispatch thread is asynchronous;
process
might not be invoked for every call to
publish
. All
Integers
published since the
last call to
process
are received as a
List
by method
process
. Lines 78-79 iterate through
this list and display the published values in a
JTextArea
. Because the computation in
method
doInBackground
progresses quickly, publishing values often, updates to the
JTextArea
can pile up on the event dispatch thread, causing the GUI to become sluggish.
In fact, when searching for a large number of primes, the
event dispatch thread
may receive
so many requests in quick succession to update the
JTextArea
that it
runs out of memory
in its event queue
. This is why we put the worker thread to
sleep
for a few milliseconds be-
tween calls to
publish
. The calculation is slowed just enough to allow the event dispatch
thread to keep up with requests to update the
JTextArea
with new primes, enabling the
GUI to update smoothly and remain responsive.
Method
done
Lines 83-98 define method
done
. When the calculation is finished or canceled, method
done
enables the
Get Primes
button and disables the
Cancel
button (lines 85-86). Line 91
gets and displays the return value—the number of primes found—from method
doIn-
Background
. Lines 93-97 catch the exceptions thrown by method
get
and display an ap-
propriate message in the
statusJLabel
.
Class
FindPrimes
Class
FindPrimes
(Fig. 23.27) displays a
JTextField
that allows the user to enter a num-
ber, a
JButton
to begin finding all primes less than that number and a
JTextArea
to dis-
play the primes. A
JButton
allows the user to cancel the calculation, and a
JProgressBar
shows the calculation's progress. The constructor (lines 32-125) sets up the GUI.
1
// Fig. 23.27: FindPrimes.java
2
// Using a SwingWorker to display prime numbers and update a JProgressBar
3
// while the prime numbers are being calculated.
4
import
javax.swing.JFrame;
5
import
javax.swing.JTextField;
6
import
javax.swing.JTextArea;
7
import
javax.swing.JButton;
8
import
javax.swing.JProgressBar;
9
import
javax.swing.JLabel;
10
import
javax.swing.JPanel;
11
import
javax.swing.JScrollPane;
12
import
javax.swing.ScrollPaneConstants;
Fig. 23.27
|
Using a
SwingWorker
to display prime numbers and update a
JProgressBar
while the prime numbers are being calculated. (Part 1 of 4.)