Search code examples
javaswing

Can I add an action listener to a JLabel?


I want to replace a JButton by a JLabel and I want my code to perform some action when the JLabel is clicked.

When I had the JButton I used action listener to handle clicks on the button:

myButton.addActionListener(new clicksListener(arg1,this))

When I replaced myButton by myLabel I got the following error message in the Eclipse:

The method addActionListener(ChipsListener) is undefined for the type JLabel

But I do know that it should be possible to attach a click handler to the JLabel. Does anybody know how it can be done?


Solution

  • Add a MouseListener to the JLabel.

    Because JLabel is a Component, you can add MouseListeners to it. Use that interface and write the mouseClicked event on your MouseListener to handle the click.