Hello Everyone. I am trying to use a string to set a color.

i have tried

Color is the string which says a color like black or red

g.setColor (Color.color);

and

g.setColor (Color."color");

lets say the string color was red it should have this effect

g.setColor (Color.red);

Thanks for any help.

I think you will have to set up a HashMap to link the Strings to actual Colors, eg

HashMap<String, Color> map = new  HashMap<String, Color>();
map.put("Red", Color.RED);
map.put("Green", Color.GREEN);
// etc

...

String colorName = "Green";
g.setColor(map.get(colorName));

Or you could use Refection to access the Color constants by name.

I'm sorry I forgot to add this, but I am working in applet. Does this work in applet?

Is this a homework question?

I'm sorry I forgot to add this, but I am working in applet. Does this work in applet?

I can't see any reason why not.

No this is not. Would you like to see my code and where I am going wrong?

Its a simple 2 player pong game. lol.

here is my code anyway.

// The "RetroPong" class.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class RetroPong extends Applet implements KeyListener, Runnable
{

    int p1x = 75, p1y = 130, p2x = 326, p2y = 130, bx = 200, by = 150, p1dy, p2dy, bdx, bdy, p1score = 0, p2score = 0;
    double colgen;
    int p1win = 0, p2win = 0;
    String color;
    Thread thread;
    HashMap map;
    private Image dbImage;
    private Graphics dbg;

    // Place instance variables here

    public void init ()
    {
        setBackground (Color.black);
        map = new  HashMap();
        map.put("red", Color.red);
        map.put("orange", Color.orange);
        map.put("yellow", Color.yellow);
        map.put("green", Color.green);
        map.put("blue", Color.blue);
        map.put("white", Color.white);
        map.put("gray", Color.gray);
        
        addKeyListener (this);
        // Place the body of the initialization method here
    } // init method


    public void start ()
    {
        thread = new Thread (this);
        thread.start ();
    }


    public void stop ()
    {
        thread.stop ();
    }


    public void run ()
    {

        Thread.currentThread ().setPriority (Thread.MIN_PRIORITY);
        while (true)
        {

            // Delay for 20 milliseconds
            try
            {
                Thread.sleep (20);
            }
            catch (InterruptedException e)
            {
            }
            Thread.currentThread ().setPriority (Thread.MAX_PRIORITY);

            if (p1y < 0)
            {
                p1dy = 0;
                p1y = 0;
            }
            else if (p1y + 40 > 300)
            {
                p1dy = 0;
                p1y = 260;
            }
            if (p2y < 0)
            {
                p2dy = 0;
                p2y = 0;
            }
            else if (p2y + 40 > 300)
            {
                p2dy = 0;
                p2y = 260;
            }
            if (bx + 10 == p2x && by + 5 < p2y + 40 && by + 5 > p2y)
            {
                bdx = -bdx;
                colgen = Math.random ();
            }
            if (bx == p1x + 5 && by + 5 < p1y + 40 && by + 5 > p1y)
            {
                bdx = -bdx;
                colgen = Math.random ();
            }

            if ((by >= p1y && by <= p1y + 5 && bx + 5 >= p1x && bx + 5 <= p1x + 5) || (by >= p2y && by <= p2y + 5 && bx + 5 >= p2x && bx + 5 <= p2x + 5))
            {
                bdy = -bdy;
                colgen = Math.random ();
            }
            if ((by <= p1y + 40 && by >= p1y + 35 && bx + 5 >= p1x && bx + 5 <= p1x + 5) || (by <= p2y + 40 && by >= p2y + 35 && bx + 5 >= p2x && bx + 5 <= p2x + 5))
            {
                bdy = -bdy;
                colgen = Math.random ();
            }

            if (by + 10 > 300)
            {
                bdy = -bdy;
                
            }
            if (by < 0)
            {
                bdy = -bdy;
            }
            if (bx < 0)
            {
                p2score += 1;
                bx = 200;
                by = 150;

            }
            if (bx > 400)
            {
                p1score += 1;
                bx = 200;
                by = 150;
            }
            if (p1score == 10)
            {
                p1win = 1;
                bdx = 0;
                bdy = 0;
                bx = 200;
                by = 0;
                repaint();
            }
            else if (p2score == 10)
            {
                p2win = 1;
                bdx = 0;
                bdy = 0;
                bx = 200;
                by = 0;
                repaint();
            }
            
            
            if (colgen > 0.8){
            color = "red";
            
            }
            else if (colgen > 0.7){
            color = "orange";
            
            }
            else if (colgen > 0.6){
            color = "yellow";
            
            }
            else if (colgen > 0.5){
            color = "green";
            
            }
            else if (colgen > 0.4){
            color = "blue";
            
            }
            
            else if (colgen > 0.2){
            color = "gray";
            
            }
            else if (colgen > 0.0){
            color = "white";
            
            }
            
            
            bx += bdx;
            by += bdy;
            p1y += p1dy;
            p2y += p2dy;
            repaint ();
        }

    }


    public void paint (Graphics g)
    {
        g.setColor (Color.white);
        g.fillRect (p1x, p1y, 5, 40);
        g.fillRect (p2x, p2y, 5, 40);
        
        g.fillOval (bx, by, 10, 10);
        g.setColor (map.get(color));
        g.drawString ("" + p1score, 5, 150);
        g.drawString ("" + p2score, 390, 150);
        if (p1win == 1)
        {
            g.drawString ("Player 1 won", 180, 150);
            g.drawString ("press n for a new game", 180, 160);
        }
        else if (p2win == 1)
        {
            g.drawString ("Player 2 won", 180, 150);
            g.drawString ("press n for a new game", 180, 160);
        }
        // Place the body of the drawing method here
    } // paint method


    public void keyPressed (KeyEvent e)
    {
        int key = e.getKeyCode ();
        if (p1win == 0 && p2win == 0)
        {


            if (key == KeyEvent.VK_UP)
            {
                p2dy = -3;

                repaint ();
            }
            else if (key == KeyEvent.VK_DOWN)
            {
                p2dy = 3;
                repaint ();
            }
            if (key == KeyEvent.VK_SHIFT)
            {
                p1dy = -3;
                repaint ();
            }
            else if (key == KeyEvent.VK_CONTROL)
            {
                p1dy = 3;
                repaint ();
            }
            if (key == KeyEvent.VK_SPACE && bdx == 0 && bdy == 0)
            {
                bdx = 2;
                bdy = 2;
                bx = 200;
                by = 150;
            }
        }
        else
        {
            p1dy = 0;
            p2dy = 0;
            bdx = 0;
            bdy = 0;
            
        }
        if (key == KeyEvent.VK_N)
        {
            p1win = 0;
            p2win = 0;
            
            bdx = 2;
            bdy = -2;
            
            p1score = 0;
            p2score = 0;
            repaint();
        }


    }


    public void keyReleased (KeyEvent e)
    {

    }


    public void keyTyped (KeyEvent e)
    {

    }


    public void update (Graphics g)
    {
        // initialize doublebuffers
        if (dbImage == null)
        {
            dbImage = createImage (this.getSize ().width, this.getSize ().height);
            dbg = dbImage.getGraphics ();
        }

        // save background
        dbg.setColor (getBackground ());
        dbg.fillRect (0, 0, this.getSize ().width, this.getSize ().height);

        // draw foreground on background
        dbg.setColor (getForeground ());
        paint (dbg);

        // Now indicate ready drawn picture Offscreen on the right screen
        g.drawImage (dbImage, 0, 0, this);
    }
} // RetroPong class

If this isn't homework then it's OK for me to collaborate!
This uses Reflection - it's not optimised or polished, but it shows the idea

public static Color getColorByName(String colorName) {
      // get all the fields declared in the Color class...
      Field[] fields = Color.class.getDeclaredFields();
      for (Field f : fields) {
         if (f.getName().equals(colorName.toUpperCase())) {
            // found a field with name matching
            try {
               // return the (Color) value of the field
               return  (Color) f.get(null);
            } catch (Exception e) {
               e.printStackTrace(); // should not happen
            }
         }
      }
      return null; // no field has a matching name
   }

Having looked v. quickly at your code I don't see why you are working with Strings for colors in the first place! Instead of

String color:
...
if (colgen > 0.8){
color = "red";
// now we have the problem of converting to an actual Color

why not

Color color
... 
if (colgen > 0.8){
color = Color.RED;
// now we have the actual Color ready to use

Thanks that worked.

ps - much shorter version of Color lookup by name...

// get a Color from a String containing a standard color name
   public static Color getColorByName(String colorName) {
      try {
         Field f = Color.class.getField(colorName.toUpperCase());
         return (Color) f.get(null);
      } catch (Exception e) {
         e.printStackTrace(); 
         return null; 
      }
   }

Thanks again everyone

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.