Coloraction Extends Abstractaction

I'm trying to extend the AbstractAction class with subclass ColorAction. This class handles the ActionPerformed method by taking the input of the user, in string format, and matching it up with a Color value within colorKey, a HashMap of String keys and Color Objects. If no Color object is found with the specified key, it will throw an exception.

For the life of me, I cant figure out how to do this. Maybe my game is off? Should I take the String input, which should be the name of a color, and check that the specified String matches one of the Color Objects? Should I make the ActionEvent equal to the user inputting a color? I have so many ideas racing through my head, with no sure winner.

public class ColorAction extends AbstractAction{
    Map<String, Color> colorMap;
    private String input;

    public ColorAction(String in) {
        input = in;
        colorMap = new HashMap<>(); //how can i enter a value that is a full range of colors?
    }

    @Override
    public void actionPerformed(ActionEvent e){
        if(colorMap.containsKey(input){
            //...
        }    
    }
}

1 Answer

If I understood your goal correctly, colorMap is an independent map predefined by you, and should therefore be static.

This is a possible way to fill a static map:

private static final Map<String, Color> colorMap = createColorMap();

private static Map<String, Color> createColorMap() {
    Map<String, Color> colorMap = new HashMap<>();

    //Fill colorMap

    return colorMap;
}

Also, you can normally get the user input by calling e.getActionCommand() in the actionPerformed method. I don't see why you would pass the user input to the ColorAction's constructor.

@Override
public void actionPerformed(ActionEvent e){
    //Assumes the map doesn't have any keys containing upper case letters.
    //By calling toLowerCase, if the user inputs "Red", it would still match
    //the key "red".
    String input = e.getActionCommand().toLowerCase();

    if(colorMap.containsKey(input){
        //...
    }    
}

That said, you probably won't need a constructor at all.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest