afzalex
afzalex

Reputation: 8652

MouseListener of parent component is not working inside child component when other MouseListener added in child

I have a JPanel parent, and a JPanel child. I have added a MouseListener in parent and another in child. Here is the code:

public void init(MouseListener listenerForParent, MouseListener listenerForChild)
{
    JPanel parent = new JPanel("Parent");
    JPanel child = new JPanel("Child");
    parent.add(child);
    parent.addMouseListener(listenerForParent);
    ...
}

Everything is working fine upto now. The mouseClicked(...) of listenerForParent is calling when I clicked I am receiving events for above code, even if I click on child JPanel, the mouseClicked(...) of listenerForParent is called.
But problem is here. When I am adding Listener in child JPanel :

public void init(MouseListener listenerForParent, MouseListener listenerForChild)
{
    JPanel parent = new JPanel("Parent");
    ...
    parent.addMouseListener(listenerForParent);
    child.addMouseListener(listenerForChild); // added new line i.e. adding MouseListener in child
}

Now when I click the child JPanel area then only the mouseClicked(...) of listenerForChild is calling.
Is it possible to get event in both listeners.

Where, I cannot modify the given MouseListeners. i.e. I cannot change mouseClicked(...) because It is given to me by some other class whose source I don't have. Therefore I cannot use dispatchEvent(AWTEvent e) method.
Thanks in advance.

Upvotes: 2

Views: 1108

Answers (1)

Fildor
Fildor

Reputation: 16049

You cannot modify it, but you can wrap it. You could put it into your own local implementation of a MouseListener and do what you have to do and then call the passed-in mouse listener.

EDIT:

Right now you are doing this:

parent.addMouseListener(listenerForParent);

but as well you could:

parent.addMouseListener(new MyLocalParentMouselistener(listenerForParent));

and implement an inner class (here: MyLocalParentMouselistener) that implements MouseListener and takes a MouseListener as Argument (and keep a reference to it). Inside, you can do this:

mouseClicked( MouseEvent e ){

    // Do some stuff here

    // assume we kept a reference to the passid-in mouseListener from 3rd Party class
    // in a class variable called "passedInMouseListenerInstance"
    passedInMouseListenerInstance.mouseClicked(e);
}

You could now do the same for the Child and pass both listeners and call them both if this is what you expect and want.

Hope it is clearer now.

Here is a tutorial on writing MouseListeners: http://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html

Upvotes: 3

Related Questions