Computer Science 225
Advanced Programming

Spring 2017, Siena College

SimpleAnimation BlueJ Project

Click here to download a BlueJ project for SimpleAnimation.


SimpleAnimation Source Code

The Java source code for SimpleAnimation is below. Click on a file name to download it.


SimpleAnimation.java

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.Timer;

/**
 * Example SimpleAnimation: roll a ball across the screen
 *
 * @author Jim Teresco, Siena College, Computer Science 225, Spring 2017
 *
 */
public class SimpleAnimation {

    public static void main(String[] args) {

        new RollingBall();
    }
}

/**
 * class to manage the JFrame that will contain the rolling ball
 * 
 * @author Jim Teresco
 */
class RollingBall extends JFrame {
 
    private static final int WINDOW_SIZE = 400;
    private static final int FLOOR_Y = 300;
    private static final int BALL_SIZE = 50;
    private static final int BALL_SPEED = 3;
    private static final int TIMER_DELAY = 20;
    
    /** current x coordinate of the rolling ball */
    private int ballX;
    
    /**
     * Construct a new RollingBall, set up for animating
     */
    public RollingBall() {
        
        // set up the JFrame
        setSize(WINDOW_SIZE, WINDOW_SIZE);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true); 
        
        // put the ball at its starting position
        ballX = -BALL_SIZE;
        
        Timer t = new Timer(TIMER_DELAY, 
            new ActionListener() {

                // the timer will wake up and call this method every
                // TIMER_DELAY milliseconds.
                @Override
                public void actionPerformed(ActionEvent e) {
                    ballX += BALL_SPEED;
                    if (ballX > WINDOW_SIZE) ballX = -BALL_SIZE;
                    repaint();
                }
        });
        t.start();
    }
    
    /**
     * paint contents of our frame
     * 
     * @param g Graphics object on which to draw
     */
    @Override
    public void paint(Graphics g) {
        
        g.setColor(Color.white);
        g.fillRect(0, 0, WINDOW_SIZE, WINDOW_SIZE);
        g.setColor(Color.black);
        g.drawLine(0, FLOOR_Y, WINDOW_SIZE, FLOOR_Y);
        g.fillOval(ballX, FLOOR_Y-BALL_SIZE, BALL_SIZE, BALL_SIZE);
    }
}