Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I add an action listener to a JLabel?

Tags:

java

swing

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?

like image 802
Roman Avatar asked Mar 10 '11 13:03

Roman


People also ask

Can I add action listener to JLabel?

Is it possible to add actionListener to JLabel? I want to click and select Jlabels for further processing. Thanks. No you can't.

Can you add an action listener to a JPanel?

First off as @Sage mention in his comment a JPanel is rather a container than a component which do action. So you can't attach an ActionListener to a JPanel .

How do I add JLabel mouse listener?

You can try : JLabel nameLabel = new JLabel("Name:"); nameLabel. addMouseMotionListener(new MouseMotionAdapter() { //override the method public void mouseDragged(MouseEvent arg0) { // to do ......................... } }); thats the way I understand your question.


1 Answers

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.

like image 146
Erick Robertson Avatar answered Oct 08 '22 10:10

Erick Robertson