Animating JFrame with Random Colors

Animating a JFrame, make it randomly colored!


Previously we've seen, animating a JFrame with a fixed background and moving on the screen. Now let's change the background of the color and that too randomly! The same concept comes, here but just a very few lines of code will be added. In this example too, i've used Threading as said earlier you can also use javax.swing.Timer class to achieve this! The following example may not be useful, but it's just art. it's just fun. it's just Swing!



Go Color it Random!


import javax.swing.*;
import java.awt.geom.*;
import java.awt.*;
import java.util.*;
class AnimatedColoredJFrame extends JFrame implements Runnable
{
Thread t;
Random r;
public AnimatedColoredJFrame()
{
// Set frame properties
setTitle("Animated JFrame");
setSize(500,500);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setUndecorated(true);

// Set some shape, i want a circle
setShape(new Ellipse2D.Double(0,0,500,500));

// Set background for the frame's content pane
getContentPane().setBackground(Color.white);

// Set opacity, don't make it opaque, that's my wish!
setOpacity(0.5f);

setVisible(true);

// Create java.util.Random object
r=new Random();

// Create a new thread, run() is written in this class (Runnable implemented)
t=new Thread(this);

// Start the thread
t.start();

}

public void run()
       {
try
{
// Get the width of the screen, so that the frame has to go till end!
int width=Toolkit.getDefaultToolkit().getScreenSize().width;

// Start the loop
for(int i=0;i<=width;i++)
{

// If i value equals width (i.e. reaches end of screen), start from starting of the screen (i.e. i=0) so looped forever
if(i==width) i=0;

// Set location, x-coordinate changes but y-coordinate is constant
setLocation(i,55);

// Set background randomly each time!
getContentPane().setBackground(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));

// Get the effect!
Thread.sleep(1);

}
}catch(Exception e){}

}

public static void main(String args[])
{
new AnimatedColoredJFrame();
}

}

Also see other swing hacks

The moving random colored transparent circular JFrame in action!




Posted by at on

Tags: Swing Hacks,