Reputation: 23
I am currently working on a small Java game in eclipse, and am knee deep in a few thousand lines of code. Right now, I am specifically attempting to use a String's contents to paint an image, and am wondering if it is possible. If it is it would save me at least a few hundred lines of individual variables for each image.
Pasting the whole program would more than likely prove counter productive due to the length, so I will merely demonstrate what I am attemtping.
What I am attempting to do:
ImageIcon ladder = new ImageIcon (getClass ().getResource ("ladder.png"));
floorContents [currentX] [currentY] = "ladder";
public void paint (Graphics g)
{
if (floorContents [currentX] [currentY] != "none") // painting item where standing
{
floorContents[currentX][currentY].paintIcon (this, g, 0, 0);
}
}
Essentially I am attempting to get the program to see this line:
floorContents[currentX][currentY].paintIcon (this, g, 0, 0);
as this:
ladder.paintIcon (this, g, 0, 0);
If at all possible. This would save me from having to write in each image item seperately.
Upvotes: 2
Views: 57
Reputation: 4157
I would kill use of strings altogether. "none" is code-smell for null
if I ever saw it. Why even match on a String
at all.
ImageIcon[][] floorContents;
ImageIcon ladder = new ImageIcon (getClass ().getResource ("ladder.png"));
floorContents[currentX][currentY] = ladder;
public void paint (Graphics g) {
if (floorContents [currentX] [currentY] != null) {
floorContents[currentX][currentY].paintIcon (this, g, 0, 0);
}
}
Upvotes: 1
Reputation: 168845
if (floorContents [currentX] [currentY] != "none")
Should be more like:
if (!floorContents [currentX] [currentY].equals("none"))
See String comparison in Java (and about 500 more) for details.
Upvotes: 1
Reputation: 347314
Put each image in a Map
keyed by the string
imageMap.put("ladder", new ImageIcon (getClass ().getResource ("ladder.png")));
//...
imageMap.get(floorContents [currentX] [currentY]).paintIcon (this, g, 0, 0);
Of course, you should key to see if the map contains the key first, or if the value returned is null...
if (imageMap.containsKey(floorContents [currentX] [currentY]) {
//....
}
of
ImageIcon image = imageMap.get(floorContents [currentX] [currentY]);
if (image != null) {
//...
}
But that's up to you
Upvotes: 2