Search code examples
c++juce

Overriding JUCE ButtonStateChange / Listener Issues


I'm struggling to figure out how to properly override a button's ButtonStateChange in the JUCE library. I'm wanting to change the what happens when a button is held down. I'm fairly new to overriding, but I've been able to successfully override other elements in the JUCE library. Though I am having an issue with this topic.

1) I know you create a new class, maybe MyCustomButton, then 2) Inherit the class you are looking to modify, Button::Listener (not sure if I should do private or public inheritance) 3) Copy and paste the code of the function you want to alter, applying the override keyword to the prototype,

but after this, I'm lost. I'm not sure how to let this new class affect a button that already exists. I know i need to add a listener to an existing button in the constructor and remove the listener in the destructor of the GUI component, but still, I don't know how to apply this new ButtonChangeState listener to an existing button.

Any help would be greatly appreciated.


Solution

  • You can create a new class which inherits from one of Juce's button classes (e.g juce::TextButton) and override buttonStateChanged()

    class MyCustomButton : public juce::TextButton
    {
    public:
        MyCustomButton();
    
    protected:
        void buttonStateChanged() override
        {
            // do what you want here
        }
    };
    

    To apply to your already existing button, just change its type to MyCustomButton.

    Alternatively, you can make the class where you use the button inherit from juce::Button::Listener and override buttonStateChanged(Button*). Then all you need is to attach the listener to your button:

    class MyWindow : public Component, private juce::Button::Listener
    {
    public:
        MyWindow()
        {
            m_button.addListener(this);
        }
    
        ~MyWindow()
        {
            m_button.removeListener(this);
        }
    
    private:
        juce::TextButton m_button;
    
        void buttonStateChanged(Button* button) override
        {
            if (button == &m_button)
            {
                // do what you want
            }
        }
    };