Java Reference
In-Depth Information
Display 19.1
Nonresponsive GUI
(part 2 of 3)
26
public
FillDemo()
27 {
28 setSize(WIDTH, HEIGHT);
29 setTitle("FillDemo");
30 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
31 setLayout(
new
BorderLayout());
32 box =
new
JPanel();
33 add(box, "Center");
34 JPanel buttonPanel =
new
JPanel();
35 buttonPanel.setLayout(
new
FlowLayout());
36 JButton startButton =
new
JButton("Start");
37 startButton.addActionListener(
this
);
38 buttonPanel.add(startButton);
39 add(buttonPanel, "South");
40 }
41
public void
actionPerformed(ActionEvent e)
42 {
43 fill( );
44 }
Nothing else can happen until
actionPerformed
returns, which
does not happen until
fill
returns.
45
public void
fill()
46 {
47 Graphics g = box.getGraphics();
48
for
(
int
y = 0; y < FILL_HEIGHT; y = y + CIRCLE_SIZE)
49
for
(
int
x = 0; x < FILL_WIDTH; x = x + CIRCLE_SIZE)
50 {
51 g.fillOval(x, y, CIRCLE_SIZE, CIRCLE_SIZE);
52 doNothing(PAUSE);
53 }
54 }
Everything stops for
100 milliseconds
(1/10 of a second).
55
public void
doNothing(
int
milliseconds)
56 {
57
try
58 {
59 Thread.sleep(milliseconds);
60 }
61 catch(InterruptedException e)
62 {
63 System.out.println("Unexpected interrupt");
64 System.exit(0);
65 }
66 }
67 }
(continued)