GTGE, unknown amount of buttons

I’m trying to generate an unknown amount of buttons by doing this:


    for (int i = 0; i < itemsList.size(); i++) {
        final String item = itemsList.get(i);
        TButton button = new TButton("" + item, 8, 415 + (25 * i), 90, 25) {
            public void doAction() {
                System.out.println("Item: " + item);
            }
        };
        this.buttons.add(button);
    }

    for (TButton button : buttons) {
        this.framework.add(button);
    }

However the framework doesn’t accept multiple buttons with the same name, so I am getting an error.

Can i generate random/unique names for each button?

Error:


Exception in thread "main" java.lang.IllegalStateException: gtge.TestGame$1@32301b86     [UIName=Button, bounds=8,415,90,25] [text=Plante] already reside in another container!!!
at com.golden.gamedev.gui.toolkit.TContainer.add(Unknown Source)
at com.golden.gamedev.gui.toolkit.FrameWork.add(Unknown Source)
at gtge.TestGame.update(TestGame.java:78)
at com.golden.gamedev.Game.startGameLoop(Unknown Source)
at com.golden.gamedev.Game.start(Unknown Source)
at com.golden.gamedev.GameLoader.start(Unknown Source)
at gtge.TestGame.main(TestGame.java:96)


You could just include the counter, i, in the name.

so


TButton button = new TButton("" + item, 8, 415 + (25 * i), 90, 25) {

becomes


TButton button = new TButton("" + item + " #"+i, 8, 415 + (25 * i), 90, 25) {

does that solve your problem?

I guess that would work, but that’d also print the number on the button itself, which is not very pretty :smiley:

well, what are the buttons representing?

It’s representing the items.

TButton button = new TButton("" + item, 8, 415 + (25 * i), 90, 25)

The item will be dropped when you click the button.

"" + item

represents the name and value of the button

The string parameter is button text; it can be anything, and does not need to be unique.

The error is because you are adding the same buttons to multiple containers.

Really, though, you should not have a button for each item. Let’s say your game includes one thousand items – do you need a button for each? No. You only need as many buttons that can be displayed on the screen at once. Then change the text, icon, and callback events according to what the button represents.