Add actionlistener to jpanel

YemSalat picture YemSalat · May 27, 2012 · Viewed 13.7k times · Source

I would like to know if there is any way to add an ActionListener to a JPanel? I have no problem adding those to JButtons, but JPanel seems not to have such a method.

Basically I have a bunch of JPanels inside a JFrame with a grid layout and I would like to know if there is any way to know when the user has clicked on one of them.

Any help much appreciated!

Answer

JB Nizet picture JB Nizet · May 27, 2012

An action listener serves to listen to action events. A button triggers an action event when it's pressed and released using the mouse (and not when it's clicked), or when it's pressed using the keyboard (space bar, mnemonic, keyboard shortcut, etc.). It's a high-level event. A mouse click is a more low-level event, which is handled by a MouseListener.

Add a MouseListener to your JPanel if you want to handle mouse clicks.