This site requires JavaScript, please enable it in your browser!
Greenfoot back
Maus2525
Maus2525 wrote ...

2018/2/9

Change text

Maus2525 Maus2525

2018/2/9

#
I want to change the text at each line (text_1, text_2, etc.) and write it in a for loop. I've seen a way of setting the image in the "Joy of Code" tutorials, and this was the example:
setImage("button" + imageNumber + ".png");
I tried to apply my idea in the same way, but it is not working as I want. Could you help me?
for (int i = 0; i < 9; i++)
{
    text = text_ + i;
    txt = new GreenfootImage(text, 24, Color.WHITE, transparent);
    background.drawImage(txt, 20, y);
    setImage(background);
    txt.clear();
    y += 30;
}
danpost danpost

2018/2/9

#
What you saw in the JOC tutorial was image files that were named appropriately to be read in a specific order. You are creating your own images and must likewise arrange them to be iterated through in some order. An array would be helpful here. You could put the created images in an array, but there is no need to keep them once they are drawn on the background image. Better would be a String array, since strings are what you start with:
private String[] texts = { "Mercury", "Venus", "Earth", "Mars", "Ceres", "Jupiter", "Saturn", "Uranus", "Neptune", "Pluto" };
Then the for loop can simply be:
for (int i=0; i<texts.length; i++)
{
    txt = new GreenfootImage(texts[i], 24, Color.WHITE, transparent);
    background.drawImage(txt, 20, i*30);
}
You need to login to post a reply.