Advertisement
rutera

How to create Animation: Paint and thread

Oct 19th, 2013
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. import java.awt.Color;
  2. import java.awt.Graphics;
  3. import java.awt.Insets;
  4. import java.util.Timer;
  5. import java.util.TimerTask;
  6.  
  7. import javax.swing.JFrame;
  8.  
  9. public class Animate extends JFrame {
  10.  
  11.   private static int DELAY = 100;
  12.  
  13.   Insets insets;
  14.  
  15.   Color colors[] = { Color.RED, Color.ORANGE, Color.YELLOW, Color.GREEN,
  16.       Color.BLUE, Color.MAGENTA };
  17.  
  18.   public void paint(Graphics g) {
  19.     super.paint(g);
  20.     if (insets == null) {
  21.       insets = getInsets();
  22.     }
  23.     // Calculate each time in case of resize
  24.     int x = insets.left;
  25.     int y = insets.top;
  26.     int width = getWidth() - insets.left - insets.right;
  27.     int height = getHeight() - insets.top - insets.bottom;
  28.     int start = 0;
  29.     int steps = colors.length;
  30.     int stepSize = 360 / steps;
  31.     synchronized (colors) {
  32.       for (int i = 0; i < steps; i++) {
  33.         g.setColor(colors[i]);
  34.         g.fillArc(x, y, width, height, start, stepSize);
  35.         start += stepSize;
  36.       }
  37.     }
  38.   }
  39.  
  40.   public void go() {
  41.     TimerTask task = new TimerTask() {
  42.       public void run() {
  43.         Color c = colors[0];
  44.         synchronized (colors) {
  45.           System.arraycopy(colors, 1, colors, 0, colors.length - 1);
  46.           colors[colors.length - 1] = c;
  47.         }
  48.         repaint();
  49.       }
  50.     };
  51.     Timer timer = new Timer();
  52.     timer.schedule(task, 0, DELAY);
  53.   }
  54.  
  55.   public static void main(String args[]) {
  56.     Animate f = new Animate();
  57.     f.setSize(200, 200);
  58.     f.show();
  59.     f.go();
  60.   }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement