Hi,

This may be a really basic query, but im not really a java expert! In my program, i am drawing rectangles and the colour of the rectangle depends on a number stored in an array, so if the number is 1 then i want to set the colour to red, if 2 then blue etc. I have to keep changing the colour a lot of times (atleast 10) so instead of writing a switch statement each time i have created the class below. The thins im having trouble calling the method in my main program. I have tried d.decide(A), but its not working. Am i calling it in the wrong way? Any help would be great!

Thanks!

import java.awt.*;
public class colors{

public Color decide(int a){
if(a==1){
return Color.red;
}
if(a==2){
return Color.blue;
}
if(a==3){
return Color.green;
}
if(a==4){
return Color.pink;
}
if(a==5){
return Color.yellow;
}
}
}

Please list the caller's source code. The function you listed does not seem to have any serious flaw.

Thats the problem i am having, could u tell me how i would call it in the main code?
Thanks

This should go in your paint function or any function for which you have a Graphics object available.

public void paint(Graphics g) {

    // your class colors... by the way,  this is not java
    // convention to lower case class names.  Should be Colors
    colors colorChooser = new colors();
  
    Color c = colorChooser.decide(A[i])
    g.setColor(c);
    // Color is now set :-)

    // now you can g.drawRect(....) with the correct color.
}

See my post here if you want to know how to use loops to step through your array.
http://www.daniweb.com/techtalkforums/showthread.php?t=9203


Hope this helps!

Ed

This article has been dead for over six months. Start a new discussion instead.