Listening to an OwnedArray of buttons (for example)


#1

has anyone got any tips, or can direct me in the direction of example code, which shows how to listen to an OwnedArray of (dynamically created) GUI components such as buttons or sliders?


#2

One thing you could do is use OwnedArray::indexOf() to get the index of the button that was clicked and do whatever logic you need with that. That could be useful.  


#3

i'm running into a wall though, cos the OwnedArray is of "TextButtons", so when i try to use ownedArray.indexOf (buttonThatWasClicked), compiler is complaining that i'm trying to initialize a type of TextButton * with a type of Button *.

 

 

 


#4

void SequencerGui::buttonClicked (Button* buttonThatWasClicked)
{
    TextButton* textPtr = static_cast<TextButton*> (buttonThatWasClicked);
    std::cout << "index = " << buttons.indexOf (textPtr) << std::endl;
}

that seems to work, but i'm a bit nervous cos it's my first timing doing a static_cast between pointer types. 

 

 


#5

I’m not that much of a C++ guru either but a static cast might be OK if you don’t use textPtr later on. Using dynamic_cast and checking against nullptr would be safer, though:

void SequencerGui::buttonClicked (Button* buttonThatWasClicked)
{
    if (TextButton* textPtr = dynamic_cast<TextButton*> (buttonThatWasClicked))
    {
        const int index = buttons.indexOf (textPtr);
        // do something
    }
}

I normally use a for loop inside buttonClicked in these cases:

void SequencerGui::buttonClicked (Button* buttonThatWasClicked)
{
    for (int i=0; i<buttons.size(); ++i)
    {
        if (buttons.getUnchecked(i) == buttonThatWasClicked)
        {
            // do something
            break;
        }
    }
}

#6

I think that is a good solution, but I personally prefer to use setComponentID() on the button to discriminate the buttonClicked event later.

When you create the buttons, add a call with setComponentID (inherited from Component obviously) and set a string to recognize the butten later on. In buttonClicked you can ask for buttonThatWasClicked->getComponentID() == "anything" to diffentiate.

The benefit is to safe the indexOf call, wich employs AFAIK a traversal of the array (if there is not an implicit index, but I don't think so).

Another plus is that you don't depend on the integrity of the order in your OwnedArray, e.g. by restyling or other changes.


#7

Oh yeah, that does sound like the best way!