Java Reference
In-Depth Information
Display 19.2
Threaded Version of FillDemo (part 2 of 3)
17
private JPanel box;
18
public static void main(String[] args)
19
{
20
ThreadedFillDemo gui = new ThreadedFillDemo();
21
gui.setVisible( true );
22
}
23
public ThreadedFillDemo()
24
{
25
setSize(WIDTH, HEIGHT);
26
setTitle("Threaded Fill Demo");
27
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
28
setLayout( new BorderLayout());
29
box = new JPanel();
30
add(box, "Center");
31
JPanel buttonPanel = new JPanel();
32
buttonPanel.setLayout( new FlowLayout());
33
JButton startButton = new JButton("Start");
34
startButton.addActionListener( this );
35
buttonPanel.add(startButton);
36
add(buttonPanel, "South");
You need a thread object, even if
there are no instance variables in
the class definition of Packer .
37
}
38
public void actionPerformed(ActionEvent e)
39
{
40
Packer packerThread = new Packer();
41
packerThread.start();
42
}
start “starts” the thread and calls run .
43
private class Packer extends Thread
run is inherited from Thread but needs to be
overridden. This definition of run is identical
to that of fill in Display 19.1.
44
{
45
public void run()
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
}
 
Search WWH ::




Custom Search