简体   繁体   中英

unexpected behavior in printing string in loop

I don't understand why this is happening:

I have an integer being passed to a label object:

int NTURNS = 3;     
for (int i = NTURNS; i > 0; i--){
printTurns(i);  
buildBall(); 
}

and printTurns is this:

private void printTurns(int i){

 GLabel turns = new GLabel("" + i);
     remove(turns);     
 add(turns, (WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));          
}

This will print the number of turns left in the game at the top. I have the remove(turns); there to remove the text so the next text won't overlap the old, but this is not working for some reason.

The numbers are stacking on top of eachother. Why is that?

You've got a bit of a GLabel problem going on there. You're creating a new GLabel for each iteration through the loop.

You should create a single GLabel , add it to the form, and then call GLabel.setLabel() to change the text for each iteration of the loop. That should save you some headaches down the road.

Somewhere in your application's form initialization (maybe constructor?):

public class MyForm : GCanvas
{
    private GLabel _turns = new GLabel();

    public MyForm()
    {
        add(_turns);
    }

    private void printTurns(int i)
    {
        _turns.setLabel("" + i);
        _turns.setLocation(WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));
    }
}

You're remove ing the new string -- which isn't there yet -- not the old one! Ie, the second time around you're remove ing "2" -- but there is no such string (as the first time you had add ed "3", not "2"!), so there's no effect. You need to remember the previous string you added, if any, eg in a private member variable, and remove that one string before you add the new one!

I had a hard time wrapping my head around Justin Niessner's answer, because I'm still new to constructors...however it did lead me to a method that worked for me. I'm putting my answer in, but I will mark his answer as correct:

private void setupGame(){

    GLabel turns = new GLabel("");   
    add(turns, (WIDTH - PADDLE_WIDTH), (BRICK_Y_OFFSET / 2));
    for (int i = NTURNS; i > 0; i--){
    turns.setLabel("" + i); 

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM