A simple Java animation example - v1
By: Nicholas Duchon

// File: MoveMeND.java
// Date: Jul 4, 2014
// Author: Nicholas Duchon
// Purpose: moving a graphic
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Container;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class MoveMeND
extends JFrame {
public static final long serialVersionUID = 123;
public
MoveMeND (String st) {
setTitle (st);
setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo (null);
setSize (400, 300);
setVisible (true);
add (new MyPanel (Color.yellow),
BorderLayout.CENTER);
validate ();
} //
end String constructor
public
static void main (String args []) {
new MoveMeND ("This Example");
} //
end main
} // end class
MoveMeND
class MyPanel extends
JPanel {
public static final long serialVersionUID = 334432;
int boxx = 10, boxy = 40, w = 250, h = 200;
int sx = boxx, sy = boxy, cx = sx, cy = sy;
int r = 6;
double t = 0, step = 1.0 / 100;
Timer timer;
Color [] aColor = {Color.red , Color.blue
, Color.green,
Color.white, Color.orange, Color.cyan };
int direction = 0;
public
MyPanel (Color c) {
setBackground (c);
timer = new Timer (10,
new ActionListener () {
public void actionPerformed (ActionEvent e) {
moveMe ();
}
} ); // end anonymous inner class and new parameter
timer.start ();
} //
end Color constructor
public void
moveMe () {
t += step;
switch (direction) {
case 0: //
diagonal
cx = (int) (sx + t*w);
cy = (int) (sy + t*h);
break;
case 1: // bottom
leftward
cx = (int) (sx - t*w);
break;
case 2: // left
upward
cy = (int) (sy - t*h);
break;
case 3: //
diagonal
cx = (int) (sx + t*w);
cy = (int) (sy + t*h);
break;
case 4: // right
upward
cy = (int) (sy - t*h);
break;
case 5: // top
leftward
cx = (int) (sx - t*w);
break;
} // end switch
repaint ();
if (t >= 1) {
t = 0;
direction =
(direction + 1) % 6;
sx = cx; sy = cy;
if (direction%3
== 0) {sx = boxx; sy = boxy;}
} // end switching direction
} //
end method moveMe
public void
paint (Graphics g) {
super.paint (g);
g.setColor (Color.black);
g.drawString ("Direction " +
direction, cx + 30, cy + 30);
g.drawRect (boxx, boxy, w, h);
g.drawLine (boxx, boxy, boxx+w,
boxy+h);
g.setColor (aColor[direction]);
g.fillOval (cx-r, cy-r, r+r, r+r);
} //
end paintComponent
} // end class
MyPanel