Mouse events

In my plugin I want to grab mouse clicks directly and make something happen at the point the user clicked. (Specifically, adding a “block” object but that isn’t the important thing.)

Here’s the relevant code :

class MyMouseListener : public MouseListener {
    MyMouseListener(GB* gb) {
        gbp = gb;
    void mouseDown(MouseEvent &event) {
        int x = event.getMouseDownX();
        int y = event.getMouseDownY();

    GB* gbp;

Then in my Component.

void GBComponent::setGBP(GB* gbp) {
    gb = gbp;    
    addMouseListener(new MyMouseListener(gbp),true); 

I know that addBlock is OK, because I’m using it elsewhere.

However, my plugin doesn’t seem to be taking notice of mouse clicks and adding the blocks at their location.

Is there anything that I’m obviously doing wrong? I know I’m not calling the superclass (MouseListener) constructor explicitly. I presume that’s happening automatically as there’s no arguments to it.

Is there something else I need to do to enable mouseEvents to find my way to this component?

Please note, every Component is already a MouseListener. So instead of adding an extra MouseListener, you can simply override mouseDown() in your GBComponent.

If you want to stick with the extra MouseListener, you have to check the following:
Is the Component you are listening to actually visible on the screen? Is setInterceptsMouseClicks() set to true? (default is yes).

Then by not capturing the result of new MyMouseListener(gbp), you are leaking memory. Instead assign it to a RAII pointer, either std::unique_ptr or ScopedPointer, so that it will be deleted, when the owner goes out of scope.


1 Like

OK. That sounds more civilized. I should have noticed that.

However, for some reason when I do it that way, Visual Studio seems to be complaining about adding

void mouseDown(MouseEvent &event) override;

to my Component header file.

mouseDown': method with override specifier 'override' did not override any base class methods  

I’d expect that to be a valid override given what you’re saying and the documentation here :

const MouseEvent&

1 Like

Ah, that was it.

Right, thanks Daniel and Xenakios. It’s now working :slight_smile: