Vishnu
Vishnu

Reputation: 12303

How to convert a String to an existing identifier in java?

private ImageIcon grasslevel0 = new
    ImageIcon("/home/vishnu/workspace/game/bin/grasslevel0.png");
JButton k = new JButton("");
k.setIcon("grasslevel"+i);

I need to convert the string "grasslevel"+i to identifier. Is that possible? If not please provide an alternative.

Upvotes: 1

Views: 462

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109597

private ImageIcon[] grasslevels = new ImageIcon[42];
for (int i = 0; i < grasslevels.length; ++i) {
    grasslevels[i] = new ImageIcon("/home/vishnu/workspace/game/bin/grasslevel"
        + i + ".png");
}
JButton k = new JButton("");
k.setIcon(grasslevels[i]);

If the number of icons is not fixed, use a List<ImageIcon> instead of [], see the answer of @Anuswadh; with grassLevels.add(new ...) and grasslevels.get(i).

The reason for this approach over a theoretical string-to-identifier, is the type-safeness; that the compiler/IDE can decide the correctness. And support typing with auto-completion.

Upvotes: 1

Melquiades
Melquiades

Reputation: 8598

That is possible to do with reflections, but is generally not advised.

private ImageIcon grasslevel0 = new ImageIcon("/home/vishnu/workspace/game/bin/grasslevel0.png");

JButton k = new JButton("");

try {
    Class c = this.getClass();
    Field f = c.getDeclaredField("grasslevel" + i);

    ImageIcon im = (ImageIcon)f.get(this);

    k.setIcon(im);

} catch (NoSuchFieldException e) {
    e.printStackTrace();
} catch (IllegalAccessException e) {
    e.printStackTrace();
}

k.setIcon(im);

Upvotes: 0

Anuswadh
Anuswadh

Reputation: 552

You always need to manually name the identifier. But you can use arraylist to store the objects.

 ArrayList<ImageIcon> grassLevel = new ArrayList<ImageIcon>();
 grassLevel.add(new ImageIcon("/home/vishnu/workspace/game/bin/grasslevel0.png"));
 grassLevel.add(new ImageIcon("/home/vishnu/workspace/game/bin/grasslevel1.png"));
 JButton k = new JButton("");
 k.setIcon(grassLevel(1));//This sets the image grasslevel1.png as the icon

Upvotes: 4

Related Questions