How do we add a button in static method?

I have a button that I have to add to my scene once this method in java gets called, I use Java to call c++ and there for the method in my scene has to be static, but I can’t add “this->addChild(button)” in that method since its static does anyone know a way I could solve this ?

You would have to make everything in your class static. But then that has other ramifications.

So why do you need a static to begin with? Can the classes be not static? Meaning what if you just backtrack removing static? I’ve seen projects where there was no good reason for using static but once you do you could end up down a rabbit hole.

1 Like

@slackmoehrle the reason

@IzzyJM you can call your AppDelegate:
(AppDelegate*)Application::getInstance())->your_method();

1 Like

Oh right. My bad I totally forgot about java. Lol.

1 Like

Where would. I call this->addChild? I call the method from my .cpp helper class , I’m confused on what the getApplicationInstance from app delegate is for?

Do you know what is AppDelegate?
From AppDelegate you can call your class.

I guess your MainMenu class will have only one instance so you can save pointer to MainMenu in some global variable and use it to call method.

You can create a singleton helper class, and store this node (Layer/Scene whatever it is you are adding to) to a property of the singleton class. Then from you static method you can call the singleton property which will point to the node.

Example (semi pseudo code):

class NodeCacheHelper {
    static NodeCacheHelper* getInstance();

    Node *yourNode = NULL;
}

Then store you’re node’s pointer: NodeCacheHelper::getInstance()->yourNode = <the node you are referring to>

Then from static method, NodeCacheHelper::getInstance()->yourNode->addChild...
Generally I wouldn’t directly call it this way, maybe singleton could have specific methods like addButton() etc.
With some null checks and correct implementation there is a solution.

This is similar to the AppDelegate solution above, but I don’t think the app delegate should contain this data and or logic.