How to use ColourSelector correctly in juce gui project

Using ColouSelector to setup the color for the controls in MianComponent.cpp in juce gui project:

MianComponent.cpp:

void MainComponent::mouseDown(const juce::MouseEvent& event)
{
     auto colourSelector = std::make_unique<ColourSelector>(ColourSelector::showAlphaChannel
    | ColourSelector::showColourAtTop
    | ColourSelector::editableColour
    | ColourSelector::showSliders
    | ColourSelector::showColourspace);

     colourSelector->setName("background");
     colourSelector->setCurrentColour(findColour(TextButton::buttonColourId));
     //(colourSelector->addChangeListener(this);   //cause it Because it error: E0167 An entity of type "MainComponent *" is incompatible with a formal parameter of type "juce::ChangeListener *". So I hchanged it to dynamic_cast<juce::ChangeListener*>(this))
     colourSelector->addChangeListener(dynamic_cast<juce::ChangeListener*>(this));
     colourSelector->setColour(ColourSelector::backgroundColourId, juce::Colours::transparentBlack);
     colourSelector->setSize(300, 400);
     colourindex = i;
     juce::CallOutBox::launchAsynchronously(std::move(colourSelector),  getScreenBounds(), nullptr);
}

juce::CallOutBox::launchAsynchronously(std::move(colourSelector), getScreenBounds(), nullptr);

void MainComponent::changeListenerCallback(juce::ChangeBroadcaster * source)
{
    if (auto* cs = dynamic_cast <juce::ColourSelector*> (source))
    {
        layers[colourindex].setBackgroundColour(cs->getCurrentColour());
        repaint();
    }
}

There is an exception thrown while compiling the program,the exception is " jassertfalse;" in the class ListenerList of juce_ListenerList.h as below shows:

void add (ListenerClass* listenerToAdd)
{
    if (listenerToAdd != nullptr)
        listeners.addIfNotAlreadyThere (listenerToAdd);
    else
        jassertfalse;  // Listeners can't be null pointers!
}

Please Help me for using ColourSelector in MianComponent of juce gui project, I will appreciate that.

You need to inherit your MainComponent from public ChangeListener. Then:

colourSelector->addChangeListener(this);

… should work correctly.

1 Like

Your MainComponent is not a ChangeListener. So using dynamic_cast<ChangeListener*>(this) will result in nullptr, because the classes are not related.

As @stephenk said, you just need your MainComponent to inherit from ChangeListener. Then you won’t need to cast a all. That will be done for you, and your original line of code will work.

This same design is true of any of the “listener” classes used in Juce. Your component needs to inherit from the specific listener type in order to add itself as a listener of that type.

1 Like

It works. thank you very much, I really appreciate it!

it works well, Many thanks.