import javax.swing.*;
import java.awt.*;
import java.util.*;
class ColorFrame extends JFrame implements Runnable
{
Thread t;
Random r;
Container pane;
public ColorFrame()
{
t=new Thread(this);
r=new Random();
pane=getContentPane();
createAndShowGUI();
}
private void createAndShowGUI()
{
setTitle("Color Frame");
setSize(400,400);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Start the thread
t.start();
// Making it 'look' like your screensaver
setUndecorated(true);
setExtendedState(MAXIMIZED_BOTH);
setVisible(true);
}
public void run()
{
while(true)
{
pane.setBackground(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
try
{
Thread.sleep(200);
}catch(Exception e){System.out.println(e);}
}
}
public static void main(String args[])
{
new ColorFrame();
}
}
Output of the ColorFrame
I got this color! |
Explaining the ColorFrame Screensaver
r=new Random(); Creates a java.util.Random object.
setExtendedState(MAXIMIZED_BOTH); This method set's the extended state of the JFrame. To set the full screen we need MAXIMIZED_BOTH which is a static variable of java.awt.Frame class.
while(true){.....} Loop for ever and ever.
pane.setBackground(....) This method is used to set the background for JFrame. This method will not directly work with JFrame, getContentPane() returns the Container of the JFrame where we can paint the background. This method takes java.awt.Color as parameter whose constructor takes 3 ints which represents the RGB values.
r.nextInt(255); Gets a random number within the range 255 from 0.
Thread.sleep(200); Choose the interval that the JFrame has to change the background. This method throws InterruptedException so it is circumscribed in try-catch.
In this way, we can easily create a dummy screensaver using Swing.