Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Thursday 18 January 2018

Java program to change window color automatically

package sWINGS;
import java.awt.*;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;

public class Animate extends JFrame {
private static int DELAY = 1000;
Insets insets;

  Color colors[] = { Color.PINK, Color.YELLOW, Color.GREEN, Color.RED,
      Color.BLUE, Color.CYAN, Color.BLACK, Color.DARK_GRAY, Color.magenta, Color.RED, Color.ORANGE };

  public void paint(Graphics graphics) {
    super.paint(graphics);
    if (insets == null) {
      insets = getInsets();
    }
  int steps=colors.length;
    int x = insets.left;
    int y = insets.top;
    int width = getWidth() - insets.left - insets.right;
    int height = getHeight() - insets.top - insets.bottom;
  
    synchronized (colors) {
    int rnd = new Random().nextInt(colors.length);
    for (int i = 0; i < steps; i++) {
        graphics.setColor(colors[rnd]);
        graphics.fillRect(x, y, width, height);
      }
    }
  }
  public void go() {
    TimerTask timerTask = new TimerTask() {
      public void run() {
        Color color = colors[0];
        synchronized (colors) {
          System.arraycopy(colors, 1, colors, 0, colors.length - 1);
          colors[colors.length - 1] = color;
        }
        repaint();
      }
    };
    Timer timer = new Timer();
    timer.schedule(timerTask, 0, DELAY);
  }
   @SuppressWarnings("deprecation")
public static void main(String args[]) {
    CreateAnimation animation = new CreateAnimation();
    animation.setSize(250, 200);
    animation.show();
    animation.go();
  }
}

No comments:

Post a Comment