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...
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.