Java 7 for Absolute Beginners

(nextflipdebug5) #1

CHAPTER 10 ■ ANIMATION


Listing 10-3. The Fireworks class

package com.bryantcs.examples.animation;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Fireworks implements ActionListener {

private static final long serialVersionUID = 1L;

FireworksPanel fireworksPanel = new FireworksPanel();
JFrame frame = new JFrame("Fireworks");
JPanel buttonPanel=new JPanel(new FlowLayout(FlowLayout.CENTER));
JButton actionButton=new JButton("Go");
boolean animating = false;
// Here's the timer, which checks for user actions
// and, if the animation is running, redraws the
// screen. It does both 25 times per second
// (1000 milliseconds divided by 40).
Timer timer = new Timer(40, this);

private void addMenu(JFrame frame) {
JMenu file = new JMenu("File");
file.setMnemonic('F');
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
exitItem.addActionListener(this);
file.add(exitItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(file);
frame.setJMenuBar(menuBar);
}

private void createAndShowGUI() {
addMenu(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new BorderLayout());
actionButton.addActionListener(this);
buttonPanel.add(actionButton);
fireworksPanel.setPreferredSize(new Dimension(400, 200));
Free download pdf