0

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?

3 Answers 3

3

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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); 

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.