Java Reference
In-Depth Information
“Wait a minute,” you may think, “the program in Display 19.1 was not supposed
to use threads in any essential way.” That is basically true, but every Java program uses
threads in some way. If there is only one stream of computation, as in Display 19.1,
then that is treated as a single thread by Java. So, threads are always used by Java, but
not in an interesting way until more than one thread is used.
You can safely think of the invocation of
Thread.sleep(milliseconds);
as a pause in the computation that lasts (approximately) the number of milliseconds
given as the argument. (If this invocation is in a thread of a multithreaded program,
then the pause, like anything else in the thread, applies only to the thread in which
it occurs.)
The method
Thread.sleep
can sometimes be handy even if you do not do any
multithreaded programming. The class
Thread
is in the package
java.lang
and so
requires no import statement.
Display 19.1
Nonresponsive GUI
(part 1 of 3)
1
import
javax.swing.JFrame;
2
import
javax.swing.JPanel;
3
import
javax.swing.JButton;
4
import
java.awt.BorderLayout;
5
import
java.awt.FlowLayout;
6
import
java.awt.Graphics;
7
import
java.awt.event.ActionListener;
8
import
java.awt.event.ActionEvent;
9 /**
10
Packs a section of the frame window with circles, one at a time.
11 */
12 public class FillDemo extends JFrame implements ActionListener
13 {
14
public static final int
WIDTH = 300;
15
public static final int
HEIGHT = 200;
16
public static final int
FILL_WIDTH = 300;
17
public static final int
FILL_HEIGHT = 100;
18
public static final int
CIRCLE_SIZE = 10;
19
public static final int
PAUSE = 100; //
milliseconds
20
private
JPanel box;
21
public static void
main(String[] args)
22 {
23 FillDemo gui =
new
FillDemo();
24 gui.setVisible(
true
);
25 }