Java Reference
In-Depth Information
60
catch
(NumberFormatException ex)
61
{
62
// display an error message if the user did not
63
// enter an integer
64
fibonacciJLabel.setText(
"Enter an integer."
);
65
return
;
66
}
67
68
// indicate that the calculation has begun
69
fibonacciJLabel.setText(
"Calculating..."
);
70
71
// create a task to perform calculation in background
BackgroundCalculator task =
new
BackgroundCalculator(n, fibonacciJLabel);
task.execute();
// execute the task
72
73
74
75
}
76
}
// end anonymous inner class
77
);
// end call to addActionListener
78
workerJPanel.add(goJButton);
79
workerJPanel.add(fibonacciJLabel);
80
81
// add GUI components to the event-dispatching thread panel
82
eventThreadJPanel.setBorder(
new
TitledBorder(
83
new
LineBorder(
Color.BLACK
),
"Without SwingWorker"
));
84
eventThreadJPanel.add(nJLabel);
85
eventThreadJPanel.add(nFibonacciJLabel);
86
nextNumberJButton.addActionListener(
87
new
ActionListener()
88
{
89
public void
actionPerformed(ActionEvent event)
90
{
91
// calculate the Fibonacci number after n2
92
long
temp = n1 + n2;
93
n1 = n2;
94
n2 = temp;
95
++count;
96
97
// display the next Fibonacci number
98
nJLabel.setText(
"Fibonacci of "
+ count +
": "
);
99
nFibonacciJLabel.setText(String.valueOf(n2));
100
}
101
}
// end anonymous inner class
102
);
// end call to addActionListener
103
eventThreadJPanel.add(nextNumberJButton);
104
105
add(workerJPanel);
106
add(eventThreadJPanel);
107
setSize(
275
,
200
);
108
setVisible(
true
);
109
}
// end constructor
Fig. 23.25
|
Using
SwingWorker
to perform a long calculation with results displayed in a GUI.
(Part 3 of 4.)