Adding ActionListener to JPanel or equivalent

Hi all.

I am trying to add an actionListener for mouse clicks on a JPanel, ideally using something like this:

panel.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent e)

{

//do something

}

});

However, JPanel does not implement addActionListener, and as far as I can see the only components which do are buttons, radio buttons and the like.

I tried extending JPanel to implement ActionListener, but had no success.

Is there an easy way to monitor for mouse clicks on a JPanel or container? Bearing in mind there will be several of these containers at different locations, so using a global mouse listener would not be useful.

Thanks

[971 byte] By [Colin_Wa] at [2007-11-26 18:47:47]
# 1

> Hi all.

>

> I am trying to add an actionListener for mouse clicks

> on a JPanel, ideally using something like this:

>

> panel.addActionListener(new ActionListener() {

>public void actionPerformed(ActionEvent e)

>{

>//do something

> }

>});

> owever, JPanel does not implement addActionListener,

> and as far as I can see the only components which do

> are buttons, radio buttons and the like.

>

> I tried extending JPanel to implement ActionListener,

> but had no success.

>

> Is there an easy way to monitor for mouse clicks on a

> JPanel or container?

Use a MouseListener.

> Bearing in mind there will be

> several of these containers at different locations,

> so using a global mouse listener would not be

> useful.

So add individual MouseListeners to each container.

>

> Thanks

Niceguy1a at 2007-7-9 6:21:44 > top of Java-index,Desktop,Core GUI APIs...
# 2

Thanks for the quick reply, had totally missed that possibility.

For anyone else interested, here's what I used:

class MouseListen extends MouseAdapter

{

public void mouseClicked(MouseEvent e)

{

//event code

}

}

panel.addMouseListener(new MouseListen());

Extending MouseAdapter means you need not implement all the MouseListener methods.

Colin_Wa at 2007-7-9 6:21:44 > top of Java-index,Desktop,Core GUI APIs...