This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Color setting Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Color setting" Watch "Color setting" New topic
Author

Color setting

Rob Hunter
Ranch Hand

Joined: Apr 09, 2002
Posts: 823
Is there a way to use 1 value to set the color of a Color object in Java? I want to pass 1 value in to set the Color. What's the easiest way to do this? Thanks.
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18712
    
    8

Yes, the Color class does have a constructor with one parameter. (public Color(int rgb).) So if your goal is to pass in one object, that would be the easiest way to do it.

Easiest at least for the code you would have to write, anyway. It delegates the complexities of building that one object to somewhere else; I don't know if that's a concern for you.
Rob Hunter
Ranch Hand

Joined: Apr 09, 2002
Posts: 823
Thanks Paul. You happen to have a good link how how to convert a value to the object expected? I'm guessing it isn't as easy as passing in a hexadecimal value? :-)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Color class constructor.

It is in fact as easy as passing a hex number.

Color red = new Color(0x00ff0000);
Rob Hunter
Ranch Hand

Joined: Apr 09, 2002
Posts: 823
Cool thanks.
Rob Hunter
Ranch Hand

Joined: Apr 09, 2002
Posts: 823
The hexadecimal way is great but here's what I'm trying to do. I need to load a value from a textfile and use that value to set the color of objects on an applet. What's the best/easiest format to store within a text file and convert it (if need be) to something that can be used to set a color? Appreciate any help on this. Thanks again.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
The nextInt() method of Scanner is probably the easiest way to extract an int from a text file.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
You could also use three ints in the range 0...255 (0...0xff) inclusive, or four floats in the range 0f...1.0f inclusive, and the three-arguments or four-arguments constructor of Color.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Color setting