Converting Strings to Color Objects

Greetings All -
I'm in my first Java class (I was a C programmer in the 80s!) and am a little stumped on an assigment. Your help will be much appreciated.
I have to read color strings out of an HTML file and put them in a HashMap (a small applet assignment). I've been unable to find an elegant method for converting from a string to a color object.
Please let me know if I'm stuck with a big nested if or am I overlooking something?
Thank you -
Gargoyle

This will handle #rrggbb strings, and also the dozen or so colors defined by name (red, cyan, etc) in the static fields of java.awt.Color:
static Color stringToColor (String s)
     try {
          return Color.decode(s);
     } catch (Exception e) {}
     try {
          return (Color) Color.class.getField(s).get(null);
     } catch (Exception e) {}
     System.out.println("bad color string: " + s);
     return null;
}

Similar Messages

  • Converting string to color

    I have a String str = "red" . how do i convert this to Color.red .

    Hmm... I see two possibilities..
    1. You make a Hashtable with entries like this:
          hash.put ("red", Color.red);
          hash.put ("blue", Color.blue);
          //etc. etc.2. You take a look what reflect can do.. ;-)
    (java.lang.reflect)
    I'd suggest the thing with the hashtable; it's easier and faster. :)
    CUL8er,
    Nick.

  • Converting String to an Object of a class

    Hi all,
    I want to convert a string to an object of a class.
    Please see my below code:
    MyClass rahul = null;
    String data = "DATA";
    rahul = (MyClass) data;
    I am getting the error: Invalid cast from java.lang.String to MyClass
    Please help me as its urgent

    There is no magical String deserialization in java. If your class can convert it's state to a string, then you will need to write the reverse parsing code, presumably using either a constructor which takes a string, or a static method similar to how numbers are handled, like:
    MyClass c = MyClass.valueOf(data);Obviously, in either case you will need to write the code to do this.

  • Converting String to Calendar Object

    Hi,
    I nedd to Change the below String to Calendar Object.i want to show the records which are older than half an hour.any other idea which will solve my problems?
    Fri Aug 17 01:56:40 GMT+05:30 1906
    Thanks in advance.
    Regards:
    Akash.

    Look at
    java.text.SimpleDataFormat

  • Convertion string to Calender object

    The input string format is "hh-mm-ss". How can I convert to Calender object.
    Can anybody suggest ?
    Thanks
    Pravat

    Use a java.text.SimpleDateFormat to convert the string to a java.util.Date object and then set the calendar object from that.

  • Issue with converting string to date object

    Hi all,
    I have a problem with sorting a list of dates in a table column. My dates are in the format 'yyyy-Mmm-dd'(Eg: 2009-Dec-23). Can someone help me how to sort the dates in this format. here is the code which i tried.
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-Mmm-dd");
              Date d1= new Date();
              Date d2= new Date();
              try {
                   d1 = dateFormat.parse("2006-Jun-09");
                 d2 = dateFormat.parse("2006-Apr-10");
              } catch (ParseException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              System.out.println("converted date 1"+ d1);
             System.out.println("converted date 1"+ d2);
    Exception : Unparseable date: "2006-Jun-09"
         }Please someone help me how to pass this date in the right format.

    I believe twisai may have lost the documentation so he/she can figure this out rather than guess that "Mmm" means 3-letter month, first letter capitalized. Let me remind him of the link:
    [http://java.sun.com/javase/6/docs/api/index.html]

  • String to xml object java

    Hello,
    can anyone suggest me how to convert string to xml object in java?
    I have a string (Data) ant now I have to pass it as parameter as xml object, which structure should be:
    <MGWData>Data</MGWData>
    Where I surf I always see only solutions for converting string to xml document, but never to xml object.
    maybe the problem is I don't completely understand what xml object is in first place :/
    Any answer would help.
    Thanks.

    894871 wrote:
    here is the method to call:
    +/**+
    * Sets the p_DATAXMLTYPEIN value for this SVARCHAR2INSERT_RECEIVESInput.
    *+
    * @param p_DATAXMLTYPEIN
    *public void setP_DATAXMLTYPEIN(com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN p_DATAXMLTYPEIN) {*
    this.p_DATAXMLTYPEIN = p_DATAXMLTYPEIN;
    one of the classes contains:
    *public class SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN  implements java.io.Serializable, org.apache.axis.encoding.AnyContentType {*
    *private org.apache.axis.message.MessageElement [] _any;*
    this method and some classes where generated using eclipse and wsdl file by creating web service client.
    wsdl says for that part: *<xsd:element name="P_DATA-XMLTYPE-IN">*
    So I suppose it should involve smth org.apache.axis.message.MessageElement. But when I create any type of parameter, it gives me error:
    + ....cannot be cast to com.oracle.xmlns.orawsv.SISTEMA_MOKA.MGW_PUBLIC_FUNCTIONS.SVARCHAR2INSERT_RECEIVESInputP_DATAXMLTYPEIN+
    I am new in web service stuff so thank you for response.Can you explain in plain English what you are trying to do? Or provide a [url http://sscce.org/]SSCE.

  • How can I convert a string to an object or class

    I would like to read a file representing a class, and convert it to an object or a class (object preferred). Other postings suggest using javax.tools.JavaCompiler to convert from a string but then say that this is not always available (posting on 1 Jan 09). If this is still not universally available is there another way to do this? If this is not available, are there any examples of how it should be done?
    My understanding from what I've read is to read the file into a String then compile the String using javax.tools.JavaCompiler, which is an Interface.
    thanks

    skidmarks wrote:
    What i would like to do is to take a Java file representing a class and compile it at runtime. However, the comment about a JDK being available at runtime makes this unattractive.So, you want to compile .java files, but you don't want to have to use a compiler?
    The next guess would to be to create a .jar file and reference it at runtime. Here's the scenario:Eh? How is that even remotely equivalent?
    1. People using the 'system' will have a varied knowledge of Java.
    2. My hope was to require that anyone using the program would only need to create a Java Class file,You mean a Java source file. You have said that YOU want to create the .class file. If they are creating the .class file, then all you need to do is load it with a ClassLoader and start using it.
    You might try clarifying your requirements a bit.
    In either case, the Class Files would look like:
    public class Name {
    int field1;
    float field2;
    } With all the field types being simple Java Primitives.What is the point of this? What are you ultimately trying to accomplish, that can be served by user-defined groups of primitives, with no complex object graphs and no user-defined methods?
    Depending on what you're really getting at, using scripting features via beanshell, groovy, or javascript might be an approach to consider, or using Scala to produce a domain-specific language (although I suspect that last may be overkill, and beyond your current skill level).
    If this is so, is there any way to create a .jar file at runtime? Do I have to exec("jar") or is there another way.A .jar file is just a .zip file with a manifest. Look at the java.util.jar package. But note that creating a .jar file has nothing to do with the rest of what you're asking about.

  • Convert String variable value  to an Object referece type

    Hi all,
    I want to know that if there any possible way to convert String variable value to a Object reference type in java. I'll explain by example if this is not clear.
    Let's think that there is a string variable name like,
    String name="HelloWorld";
    and there is a class name same to the variable value.
    class HelloWorld
    I am passing this string variable value to a method which is going to make a object of helloworld;
    new convertobj().convert("HelloWorld");
    class convertobj{
    public void convert(String name){
    // in hert it is going to create the object of HelloWorld;
    // HelloWorld hello=new HelloWorld(); just like this.
    now i want to do this from the name variable value.( name na=new name()) like wise.
    please let me know if there any possible way to do that.
    I am just passing the name of class by string variable then i wanted to make a instance of the class which come through the variable value.
    thanx.

    Either cast the object to a HelloWorld or use the reflection API (Google it) - with the reflection API you can discover what methods are available.
    Note: if you are planning to pass in various string arguments and instantiate a class which you expect to have a certain method... you should define an interface and have all of your classes that you will call in this way implement the interface (that way you're sure the class has a method of that name). You can then just cast the object to the interface type and call the method.
    John

  • How to pass a String and make it as Color Object

    I need to set a background color dynamically...but the value that i pass is in string format. How can i convert the string into Color format so that i can use the method setBackground(Color.blue) method. How to pass the string into the 'Color.blue' ?

    Let param="red"
    Class cls = Class.forName("java.awt.Color");
    java.lang.reflect.Field fld = cls.getDeclaredField(param);
    Color clr = (Color)fld.get(null);
    You can use this 'clr' variable as you wish.
    null

  • How to convert a string to date object?

    I have a string user input for date.
    I want to convert it to Date object to insert it in database.
    How to do it?

    Check the java.text.SimpleDateFormat class. You can use it for parsing dates. API contains good description how to build the format pattern.
    HTH
    Mike

  • Getting Color object from String

    hi
    i need to get a Color object from a string provided at runtime.ie for the string "RED" i need to get a object of Color.RED.I have already tried to use decode() from Color class but it throws numberformat exception,can someone guide me.

    Color.decode(String) will decode octal and hexidecimal representations of colors e.g.
    Color poo = Color.decode("0x215DB8"); // hex description of color
    works.
    If you want to use RED, BLUE ... read them at run into a String or whatever and then test this String to get what color the user wanted e.g.
    read from text file at run time that button colour should be ORANGE.
    In your code, put
    String colourStr; // read what colour the user specified into this var
    Color their_color = null;
    if(colour.equals("ORANGE"))
    their_color = new Color(Color.orange);
    else if(colour.equals("BLACK"))
    // you can guess what goes here.. and so on.
    It often nice to make them specify the hex value of the colour because there are more of these than the predefined colours (shock horror).
    Anyway,
    seeya, Edd.

  • Converting a String to an Object

    Is there some way of converting a String (from a textfield) to an Object? What I want is something similar to the functionality offerred by a JTable. This is because I want the user to be able to input a value of any type to the textfield (e.g. String, int, boolean, etc) and get its object representation ...
    Would a simple cast do ?
    David

    dattard,
    A string is an object, when someone enters something into a JTextField, REGARDLESS of what it is (int, double, string, etc) it is stored in the string text in that text field (JTextField.getText()).
    So if someone enters in "123", its the STRING 123, not the number one hundred and twenty three... to GET the number 123, you'll need to do something like:
    int value = Integer.parseInt( myTextField.getText() );
    to have the string parsed for the value, if you want a double, same idea:
    double value = Double.parseDouble( myTextField.getText() );
    NOTE: The number wrapper classes (Integer, Double, Float, etc.) contain "parseXXXX" methods that allow you to parse a corresponding numeric value out of a String object.
    Also, when a user enters ANYTHING into a text input field of any type, its ALWAYS a String, if you want a different version of what they entered, its up to you to parse it and decide what it was.

  • Convert strings to publicKey/privateKey objects

    Hi,
    I have the following problem : I'm generating RSA key pairs in string formats. I want to sign an XML document so I have to specifiy KeyPair object in order to do that.
    How can I convert string to publicKey and privateKey objects ?
    i.e How can I correct this code :
    String pubKey = generatePublicKey();
    String priKey = generatePrivateKey();
    KeyPair kp = new KeyPair(pubKey,priKey);
    // sign the XML documents
    Thanks a lot for your precious help.
    Cheers,
    Othman.

    http://forum.java.sun.com/thread.jspa?threadID=577716&tstart=0

  • Question on converting #FFFFFF to Color

    Yea, I'm new at this but am having fun!. I have written an applet to replace and applet that I downloaded a few months ago. I need to set the colors of the foreground and background from <PARAM> tags in html. My question is how can I convert #FFFFFF that will be in the param tag to a Color object for setForeground() and setBackgroud()? I'm using a swing Applet.

    Test this little program that convert any hexadecimal color to an RGB color :
    import java.awt.*;
    public class ColorConverter {
         public static void main(String[] args) {
              getColorFromHtml(0xffffff);
              getColorFromHtml(0xff0000);
              getColorFromHtml(0x00ff00);
              getColorFromHtml(0x0000ff);
         public static Color getColorFromHtml(int htmlColor) {
              int red = htmlColor>>16;
              int green = (htmlColor>>8)&0x00ff;
              int blue = htmlColor&0x0000ff;
              System.out.println("red :" +red+" green : "+green+" blue : "+blue);
              return(new Color(red, green, blue));
    }------ unformatted version -----
    import java.awt.*;
    public class ColorConverter {
         public static void main(String[] args) {
              getColorFromHtml(0xffffff);
              getColorFromHtml(0xff0000);
              getColorFromHtml(0x00ff00);
              getColorFromHtml(0x0000ff);
         public static Color getColorFromHtml(int htmlColor) {
              int red = htmlColor>>16;
              int green = (htmlColor>>8)&0x00ff;
              int blue = htmlColor&0x0000ff;
              System.out.println("red :" red" green : "+green+" blue : "+blue);
              return(new Color(red, green, blue));
    Before that you have to convert the string #FFFFFF to an int :
    String s = "#FFFFFF";
    s = s.substring(1);
    int hexColor = Integer.parseInt(s, 16);
    Color rgb = getColorFromHtml(hexColor);
    Denis

Maybe you are looking for