// BasicGraphicsWithTimer.java // Same as BasicGraphics.java, but with a Timer for animation! // A simple shell for drawing graphics as described in our textbook. // Note that this is an *application* whereas the book uses *applets*. // This should have little impact on you, however. import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; public class BasicGraphicsWithTimer extends JComponent implements ActionListener { public static void main(String[] args) { JComponent myGraphics = new BasicGraphicsWithTimer(); // Your class name goes here! launch(myGraphics, 500, 300); // Set the initial dimensions here! } public void onTimer() { // PUT YOUR ANIMATION CODE HERE // For example: circleX = (circleX + 5) % getWidth(); } public void paint(Graphics page) { if (this.timer == null) { // start the timer the first time paint is called! int timerMillis = 1; // # of milliseconds between timer calls timer = new javax.swing.Timer(timerMillis, this); timer.start(); } int width = getWidth(); int height = getHeight(); // paint a blue rectangle as large as the window page.setColor(Color.blue); page.fillRect(0,0,width,height); // paint a yellow circle at location x,y page.setColor(Color.yellow); page.fillOval(circleX, circleY, 50, 50); } public void actionPerformed(ActionEvent e) { onTimer(); repaint(); } private javax.swing.Timer timer; private int circleX, circleY; ////////////////////////////////////////////////////////////////////////////// ///////////////// END OF YOUR CODE ///////////////////// ///////////////// (you may ignore all the code below!!! ///////////////////// ////////////////////////////////////////////////////////////////////////////// public static void launch(JComponent jc, int width, int height) { JFrame frame = new JFrame(jc.getClass().getName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel cp = new JPanel(); cp.setLayout(new BorderLayout()); cp.add(jc); frame.setContentPane(cp); frame.setSize(new Dimension(width,height)); frame.setVisible(true); } }