Java Reference
In-Depth Information
fireworksPanel.setBackground(Color.WHITE);
frame.getContentPane().add(fireworksPanel,BorderLayout.CENTER);
frame.getContentPane().add(fireworksPanel);
frame.getContentPane().add(buttonPanel,BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
Fireworks fireworks = new Fireworks();
fireworks.createAndShowGUI();
}
// This method listens to the timer. The
// program goes through it every 40
th
of a
// second, giving us a Hertz or frame rate of 25.
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand() != null) {
// Check for the user choosing Exit
// from the file menu and exit if so
if (e.getActionCommand().equals("Exit")) {
System.exit(0);
}
// Check for the Go button being clicked and, if so,
// start the animation and set the button to Stop
if (e.getActionCommand().equals("Go")) {
animating = true;
timer.start();
actionButton.setText("Stop");
}
// Check for the Stop button being clicked and, if so,
// stop the animation and set the button to Go
if (e.getActionCommand().equals("Stop")) {
animating = false;
timer.stop();
actionButton.setText("Go");
}
}
// If the animation is running (the user has
// clicked Go but not Stop), repaint the window
// which is how we create the animation).
if (animating){
fireworksPanel.repaint();
}
}
}
Now let's look at the Fireworks drawing panel. The use of a
Timer
object in the Fireworks class
simplifies this class, too. We no longer need to implement the
Runnable
interface, have a
run
method, or
specify when to repaint. Again, the
Timer
class does all that for us, letting us focus on drawing the
collection of objects we want on the panel. Listing 10-4 shows the
FireworksPanel
class.