Create a dummy Screensaver using Swing

The following program illustrates creating a dummy screensaver which is not at all a screensaver. I couldn't call it as a screensaver rather i could call it as a dummy screensaver because it just looks like a screensaver. Just don't comment about whether it is a screensaver or not because this post is not going to be all about the screensaver and it's stuff. It's gonna be fun with Swing. Let's start coding!

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();
        private void createAndShowGUI()
        setTitle("Color Frame");
        // Start the thread
        // Making it 'look' like your screensaver
        public void run()
            pane.setBackground(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
                }catch(Exception e){System.out.println(e);}
        public static void main(String args[])
            new ColorFrame();

Output of the ColorFrame

Dummy Screensaver Screenshot
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.

Posted by at on

Tags: Swing Hacks,