What am I doing wrong for addAndMakeVisible?


#1

[code] void addNewTabFile()
{
MainComponent test;
//MainComponent theMainComponent;
//test = new MainComponent;

	Component::addAndMakeVisible (test,0);
	//test->setBounds (0, 0, getWidth(), getHeight());
}[/code]

Can anyone help?

Thanks ahead of time.

-Angelo


#2

Assuming that addNewTabFile() is a function belong to a class derived from the Component class, you’ll want to pass a pointer to your component to addAndMakeVisible:

void addNewTabFile() { MainComponent test; addAndMakeVisible (&test, 0); ... }

or

void addNewTabFile() { MainComponent* test = new MainComponent; addAndMakeVisible (test, 0); ... }


#3

You don’t want to addAndMakeVisible to locally created objects. First, they go out of scope when you exit out of the routine since they are created on the stack. Second, the destructor for a component deletes any added children and it will be deleting an invalid pointer.

The best way to add components is always to dynamically allocate them:

Component c = new Component(T("My Component")); addAndMakeVisible(c); c->setBounds(100, 100, 400, 300);
If you have another component already allocated somewhere else and don’t want it deleted automatically after adding it to the main component, call in the parent component’s destructor:removeChildComponent(c);

  • kbj

#4

In other words, do:

[code]void addNewTabFile()
{
MainComponent *test new MainComponent;

Component::addAndMakeVisible (test,0);
test->setBounds (0, 0, getWidth(), getHeight());

}[/code]

And make sure you call deleteAllChildren() in the destructor, or something equivilent.


#5