Theinput in a JTextField must be used in the variable Color color.
input = YELLOW must change variable color in Color.YELLOW.
My attempt does not work:

6 Years
Discussion Span
Last Post by JamesCherrill

// to solve how to use input tekst in variable kleur

    public Color getInvoer()
            String tekst = kleurTekstVeld.getText();
            kleur = Color.tekst;
            return kleur;

You will need to convert the String obtained from the textfield to a Color object.
One way would be to use a chain of if/else if statements to compare the String and set the Color, or switch with 1.7,
another would be to use a Map<String, Color> that has been loaded with colors and their names as strings

Edited by NormR1


When you seeColor.xxx the xxx is the name of a public variable in the Color class. You can't just use a String variable as the name like that.
There are (at least) two ways to do what you want:
1. Create a Map<String, Color> that has the string as a key and the actual Color as the value ( map.add("yellow", Color.yellow); etc), the use that to look up the Color from the user's input string. See http://www.daniweb.com/software-development/java/threads/341974/using-a-string-to-set-a-color
2. Use Reflection to access the Color variable by name using the input String in Class's getField method - but this would count as "advanced" Java in most books.

Edited by JamesCherrill


The proposed solution using HashMap was new to me. The change from text input to color can also be done with the switch statement of which I have an explanation in dutch. I made following code and it works. If it is nice code?

class kleurTekstVeldHandler implements ActionListener
    public void actionPerformed(ActionEvent e) 
        input = kleurTekstVeld.getText();
        color =(Color) getInput();
        //copied from book page 45 book 3 OU
        Container inhoud = getContentPane();
        for(Component c: inhoud.getComponents()){
            if( c instanceof JButton){

// solved with switch instruction input in variable color
public Color getInput(){
    String input = kleurTekstVeld.getText();
    return color;

public Color giveColor(String input){
switch (input){
case "red":
return color = Color.red;
case "green":
return color = Color.green;
return color = Color.black;

Edited by cor.vandijk.779


The switch is a perfectly reasonable solution - a little bit longer than the Map, but works just as well for a relatively small and fixed set of colors.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.