Take the 2-minute tour ×

The following code consist of method that is overridden to make pattern of rectangle. I wanted to give different color to each rectangle. Do you have any idea how this can be done ?

  public void actionPerformed(ActionEvent event) {
        int x1 = 60;
        int y1 = 60;
        int width = 280;
        int length = 140;

        Graphics paper = panelForBackGround.getGraphics();
        for (int x = 1; x < 8; x++) {

            paper.draw3DRect(x1, y1, width,length, true);
            x1 = x1 + 10;
            y1 = y1 + 10;
            width = width - 20;
            length = length - 20;

share|improve this question
add comment

2 Answers

Colors can be created using RGB values. Create three random numbers between 0 and 255 (boundaries included) and apply the resulting color to your rectangle.

share|improve this answer
which class and method should I use. I started with java a week ago. –  user1837224 Dec 7 '12 at 16:57
add comment

At top of file:

import java.util.Random;
import java.awt.Color;

At top of method:

Random random = new Random();

In loop before you draw:

paper.setColor(new Color(random.nextInt()));


share|improve this answer
Thanks , it's working but may I know what do these three lines do ? –  user1837224 Dec 7 '12 at 17:00
There is that thing called Javadoc, which contains documentation on what classes and methods do... one of the key skills a programmer needs is the diligence to work trough existing documentation. –  Durandal Dec 7 '12 at 18:07
I added links. If you like my answer, up-vote it :) –  mikeslattery Dec 7 '12 at 22:24
add comment

Your Answer


