Timer and TimerTask in Java Swing

We use java.util.Timer for threads.This class provides schedule tasks for future execution in a background thread. We use java.util.TimerTask to set scheduled for one-time or repeated execution by a Timer.

 

import java.awt.*;

import java.util.Timer;

import java.util.TimerTask;

import javax.swing.JFrame;

public class ani extends JFrame

{

private static int WAIT = 150;

Insets insetss;

//multiple colors

Color coloors[] = { Color.GRAY, Color.PINK, Color.RED,Color.CYAN,Color.GRAY };

public void paint(Graphics graphics)

{

   super.paint(graphics);

   if (insetss == null)

{

     insetss = getInsets();

   }

int steps=coloors.length;

   int xx = insetss.left;

   int yy = insetss.top;

   int widtth = getWidth() - insetss.left - insetss.right;

   int heightt = getHeight() - insetss.top - insetss.bottom;

   synchronized (coloors)//for multiple colors run simultaneously

{

     for (int i = 0; i < steps; i++)

{

       graphics.setColor(coloors[i]);

       graphics.fillRect(xx, yy, widtth, heightt);

     }

   }

}

public void goo()

{

   TimerTask timerTask = new TimerTask()

{

     public void run()

{

       Color color = coloors[0];

       synchronized (coloors)

{

         System.arraycopy(coloors, 1, coloors, 0, coloors.length - 1);

         coloors[coloors.length - 1] = color;

       }

       repaint();

     }

   };

   Timer time = new Timer();

   time.schedule(timerTask, 0, WAIT);

}

   public static void main(String aa[])

{

   ani animation = new ani();

   animation.setSize(250, 200);

   animation.show();

   animation.goo();

}

}

Multiple colors in java swing

Explanation…

Java.util package is used for Swing Timers. This program shows how to create an animation with multiple colors.In this program, colors are displayed one by one from the list of colors. There are 13 Color instances already defined as static field of Color (white,black, red,green, pink,orange, magenta, yellow,gray,lightgray,darkgray,green,blue)