简体   繁体   中英

Convert String to java.awt.Color

I'm trying to convert a String object to a java.awt.Color object.

I am scanning the input color from an user. The user enters a color and the color is saved in a String . I want to put that color into an ArrayList of colors from the String . How do I do that?

Scanner sc = new Scanner(System.in);
System.out.println("\nEnter your color\n" + 
                       "BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");

String str = sc.next();
str = str.toUpperCase();

private ArrayList<Color> colorArray= new ArrayList<Color>();

// Here I want to put the colors (string str) in the colorArray arraylist.

How do I achieve this?

How about doing it through reflection?

 Color color = (Color)Color.class.getField(str).get(null);
 colorArray.add(color);

You might want to do some exception handling in case the user enters a color that is not a field in the Color class.

However, note that this technique will work only for certain basic colors for which the class java.awt.Color provide static instance members. Eg the class currently provides the following static instance members only:

  • black
  • blue
  • cyan
  • darkGray or DARK_GRAY
  • lightGray or LIGHT_GRAY
  • gray
  • green
  • magenta
  • orange
  • pink
  • red
  • white
  • yellow

For other colors like turquoise, you will have to build the Color object using an appropriate RGB combination.

Here is an example of how you could do it with a bit of Java 9:

public static void main(String[] args) throws ParseException, ClassNotFoundException {
    Scanner sc = new Scanner(System.in);
    System.out.println("\nEnter your color\n" +
            "BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");

    List<Color> colorArray= new ArrayList<>();
    Map<String, Color> colorMap = Map.ofEntries(entry("BLUE", Color.BLUE),
            entry( "BLACK", Color.BLACK),
            entry( "ORANGE", Color.ORANGE)); // TODO: add more colours
    while(sc.hasNext()) {
        String next = sc.next();
        Color c = colorMap.get(next);
        if(c == null) {
            if("END".equals(next)) {
                break;
            }
            System.err.printf("Sorry, could not find %s%n", next);
        }
        else {
            colorArray.add(c);
            System.out.printf("Added %s%n", c);
        }
    }
    System.out.println(colorArray);
}

This is the output of a sample run:

Enter your color
BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:
> BLUE
Added java.awt.Color[r=0,g=0,b=255]
> BLACK
Added java.awt.Color[r=0,g=0,b=0]
> ORANGE
Added java.awt.Color[r=255,g=200,b=0]
> END
[java.awt.Color[r=0,g=0,b=255], java.awt.Color[r=0,g=0,b=0], java.awt.Color[r=255,g=200,b=0]]

Here is another version based on @VHS ideas using reflection:

public static void main(String[] args) throws ParseException, ClassNotFoundException, IllegalAccessException {
    Scanner sc = new Scanner(System.in);
    System.out.println("\nEnter your color\n" +
            "BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
    List<Color> colorArray= new ArrayList<>();
    Class<Color> colorClass = Color.class;
    while(sc.hasNext()) {
        String next = sc.next();
        try {
            Color c = colorClass.cast(colorClass.getField(next.toLowerCase()).get(null));
            colorArray.add(c);
            System.out.printf("Added %s%n", c);
        } catch (NoSuchFieldException e) {
            if("END".equals(next)) {
                break;
            }
            System.err.printf("Sorry, could not find %s%n", next);
        }
    }
    System.out.println(colorArray);
}

Ideally you would combine both ideas (use a map and reflection), so that you support the declared colours + non declared colours in java.awt.Color.

public class TestProj {

    public static void main (String[] args)throws IOException {
        List<Color> colorArray= new ArrayList<Color>();
        Scanner sc = new Scanner(System.in);
        System.out.println("\nEnter your color\n" + 
                               "BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");

        while(sc.hasNext()){
            String str = sc.next();
            str = str.toUpperCase();
            colorArray.add(new Color(str));
        }
        System.out.println("Array size: " + colorArray.size());
    }

    static class Color {
        private String color;

        public Color(String color){
            setColor(color);
        }

        public String getColor() {
            return color;
        }

        public void setColor(String color) {
            this.color = color;
            System.out.println(color);
        }



    }

}

My output is (Ctrl-Z to terminate loop): Enter your color BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:

BLUE BLACK ORANGE

BLUE

BLACK

ORANGE

Array size: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM