Java by Example - random colors and arrays

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 next

This example combines nested loops, random numbers and "custom made" colors. Since colors are defined by their Red, Green and Blue fraction, ranging from 0 to 255, we have to generate three random numbers in that range to generate random colors. In order to get a clear picture, we need to make sure the colors are not generated in the paint() method every time Java paints the applet new by default. We need a way to create 100 colors in a controlled way at a time we wish. To do this we need to introduce arrays. Arrays can hold several variables of the same type (int, float, String, Color, Font etc.) which can be accessed through one name and an index number. This makes it especially easy to access them inside a loop. Since arrays are "real" objects in Java, we have to declare them and then instanciate them with "new".

So in this program the color array is filled only once (inside the init()-method) and we use double buffering and a thread (updated 10 times a second here) to ensure everything gets drawn correctly without flicker. Instead of putting the drawing functions directly into the paint() method, we put that part into a drawColors() method, which is called from the paint() method.

//Sourcecode

import java.awt.*;
import java.applet.*;

public class Project16 extends Applet implements Runnable
{
    Image Buffer;
    Graphics gBuffer;
    //declare an array variable to hold our Colors
    Color myColors[];
    Thread runner;

    public void init()
    {
        //create off-screen image we can draw to
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();

        //arrays are real objects, we have to declare them with "new"
        myColors = new Color[100];

        for(int i=0;i<100;i++)
        {
            int red=(int)(Math.random()*255);
            int green=(int)(Math.random()*255);
            int blue=(int)(Math.random()*255);

            //fill our array with random colors
            myColors[i]=new Color(red, green, blue);
        }
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            //halt the thread for 100 ms here
            try {runner.sleep(100);}
            catch (Exception e) { }

            repaint();
        }
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    public void drawColors()
    {
        //draw tiles with random colors
        //we use two nested loops to do this:

        int i=0;

        for(int x=0;x<300;x+=30)
            for(int y=0;y<300;y+=30)
            {
                gBuffer.setColor(myColors[i]);
                gBuffer.fillRect(x,y,60,60);

                //increment the index of our array here
                i++;
            }
        }

        public void paint (Graphics g)
        {
            drawColors();

            //copy the buffer to the screen
            g.drawImage (Buffer,0,0, this);
        }
}

This applet adds automatic refresh of our color applet once a second, so we add a getNewColors() method, which is called once in a second, to get 100 new colors for our array.

//Sourcecode

import java.awt.*;
import java.applet.*;

public class Project17 extends Applet implements Runnable
{
    Image Buffer;
    Graphics gBuffer;
    //declare an array variable to hold our Colors
    Color myColors[];
    Thread runner;

    public void init()
    {
        //create off-screen image we can draw to
        Buffer=createImage(size().width,size().height);
        gBuffer=Buffer.getGraphics();

        //arrays are real objects, we have to declare them with "new"
        myColors = new Color[100];
    }

    public void getNewColors()
    {
        for(int i=0;i<100;i++)
        {
            int red=(int)(Math.random()*255);
            int green=(int)(Math.random()*255);
            int blue=(int)(Math.random()*255);

            //fill our array with random colors
            myColors[i]=new Color(red, green, blue);
        }
    }

    public void start()
    {
        if (runner == null)
        {
            runner = new Thread (this);
            runner.start();
        }
    }

    public void stop()
    {
        if (runner != null)
        {
            runner.stop();
            runner = null;
        }
    }

    public void run()
    {
        while(true)
        {
            //halt the thread for 1000 ms here
            try {runner.sleep(1000);}
            catch (Exception e) { }

            //get new colors every second
            getNewColors();

            repaint();
        }
    }

    public void update(Graphics g)
    {
        paint(g);
    }

    public void drawColors()
    {
        //draw tiles with random colors
        //we use two nested loops to do this:

        int i=0;

        for(int x=0;x<300;x+=30)
            for(int y=0;y<300;y+=30)
            {
                int red=(int)(Math.random()*255);
                int green=(int)(Math.random()*255);
                int blue=(int)(Math.random()*255);

                gBuffer.setColor(myColors[i]);
                gBuffer.fillRect(x,y,60,60);

                //increment the index of our array here
                i++;
            }
    }

    public void paint (Graphics g)
    {
        drawColors();

        //copy the buffer to the screen
        g.drawImage (Buffer,0,0, this);
    }
}

back 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 next

0 - setup - getting your tools ready
1 - basic graphics functions
2 - simple methods and basic data types
3 - IF, ELSE and SWITCH: basic control structures
4 - introducing the operators
5 - methods with and without a return value
6 - using methods and basic mouse functions
7 - fonts, random numbers and timers
8 - flicker free graphics, GIF and JPEG display
9 - animation with GIF pictures, sprite animation
10 - loops, advanced color functions
11 - random colors and arrays
12 - digital clocks, HTML page parameters
13 - introducing classes and objects
14 - using the Vector class
15 - using mouseMove and mouseDrag
16 - keyboard commands and playing sound
17 - detecting collisions and intersections
18 - a Bouncing Balls applet
19 - fun with letters and words
20 - rotating lines and polygons
21 - sorting and shuffling


© 2000 by Johannes Wallroth
www.programming.de

watson@programming.de