Java Reference
In-Depth Information
11
import
javax.swing.JTextField;
12
import
javax.swing.border.TitledBorder;
13
import
javax.swing.border.LineBorder;
14
import
java.awt.Color;
15
import
java.util.concurrent.ExecutionException;
16
17
public class
FibonacciNumbers
extends
JFrame
18
{
19
// components for calculating the Fibonacci of a user-entered number
20
private final
JPanel workerJPanel =
21
new
JPanel(
new
GridLayout(
2
,
2
,
5
,
5
));
22
private final
JTextField numberJTextField =
new
JTextField();
23
private final
JButton goJButton =
new
JButton(
"Go"
);
24
private final
JLabel fibonacciJLabel =
new
JLabel();
25
26
// components and variables for getting the next Fibonacci number
27
private final
JPanel eventThreadJPanel =
28
new
JPanel(
new
GridLayout(
2
,
2
,
5
,
5
));
29
private long
n1 =
0
;
// initialize with first Fibonacci number
30
private long
n2 =
1
;
// initialize with second Fibonacci number
31
private int
count =
1
;
// current Fibonacci number to display
32
private final
JLabel nJLabel =
new
JLabel(
"Fibonacci of 1: "
);
33
private final
JLabel nFibonacciJLabel =
34
new
JLabel(String.valueOf(n2));
35
private final
JButton nextNumberJButton =
new
JButton(
"Next Number"
);
36
37
// constructor
38
public
FibonacciNumbers()
39
{
40
super
(
"Fibonacci Numbers"
);
41
setLayout(
new
GridLayout(
2
,
1
,
10
,
10
));
42
43
// add GUI components to the SwingWorker panel
44
workerJPanel.setBorder(
new
TitledBorder(
45
new
LineBorder(
Color.BLACK
),
"With SwingWorker"
));
46
workerJPanel.add(
new
JLabel(
"Get Fibonacci of:"
));
47
workerJPanel.add(numberJTextField);
48
goJButton.addActionListener(
49
new
ActionListener()
50
{
51
public void
actionPerformed(ActionEvent event)
52
{
53
int
n;
54
55
try
56
{
57
// retrieve user's input as an integer
58
n = Integer.parseInt(numberJTextField.getText());
59
}
Fig. 23.25
|
Using
SwingWorker
to perform a long calculation with results displayed in a GUI.
(Part 2 of 4.)