Saving Component State


#1

Hi,

I have a menu which allows the user to show different components. I’m using the following code for when a menu item is selected…

void menuItemSelected(int menuItemID, int toplevelMenuIndex)
{
if(menuItemID==1 && toplevelMenuIndex==0){
//to show the home page
delete currentComponent; //currentComponent is initialised to mainWindow in the constructor
mainWindow->setBounds(0, 50, 1000, 550);
this->addAndMakeVisible(mainWindow);
currentComponent = mainWindow;
}
else if(menuItemID==2 && toplevelMenuIndex==0){
//to show the device setup page
delete currentComponent;
setup->setBounds(0, 50, 1000, 550);
this->addAndMakeVisible(setup);
currentComponent = setup;
}
}

My app loads fine and I can bring up the audio device page ok too. However, when I try to return to the home page (mainWindow) the app crashes. I’ve also tried setContentComponent() instead of addAndMakeVisible() but it gives the same result.

Any help is appreciated, I’m sure this is a simple fix.

Thanks…


#2

Two pieces of advice:

  1. Learn to use ScopedPointers instead of ‘delete’.
  2. Learn to use your debugger.

#3

Well I know how to use my debugger, not great on scoped pointers though. It seems that it was crashing because I was deleting the component and then trying to make it visible. I’m working around it by setting its visibility to false when I don’t need to see it, instead of deleting it. It works and hasn’t caused any problems so far. Do you think its bad programming though?


#4

I’ve no idea what your app needs to do, so can’t judge whether hiding would be better than deletion in your case. But if you avoid deleting something because you don’t understand how to manage pointers and object lifetimes safely, then yes, that certainly sounds like bad programming!

Get familiar with ScopedPointers, it’ll help a lot.