Roman
Roman

Reputation: 131128

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?

Upvotes: 20

Views: 65344

Answers (4)

Eric Lang
Eric Lang

Reputation: 274

Sure. JLabels have a method which allow you to attach a MouseListener object. The MouseListener object requires a MouseAdapter() object. MouseAdapter is an abstract class which ideally serves as an Adapter for for creating on the fly listeners to do things.

JLabel label = new JLabel("<An image icon, if you'd like>");

// now lets attach a listener to your JLabel
lb.addMouseListener(new MouseAdapter() 
{
    @Override
    public void mouseClicked(MouseEvent e) 
    {
        // THIS CODE WILL RUN WHEN THE EVENT OF CLICKING IS RECEIVED.
        // example of something you could do below.
        new Random().ints().limit(60).forEach(System.out::println);
    }
});

Upvotes: 3

kupaff
kupaff

Reputation: 329

/*add a mouselistener instead and listen to mouse clicks*/
    jlable.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    System.out.println("Yay you clicked me");
                }

            });

Upvotes: 12

camickr
camickr

Reputation: 324118

An easier approach is to just use a JButton since it already supports this functionality by using an ActionListener.

You can make the JButton look like a JLabel by using:

button.setBorderPainted( false );

This approach is for when you want to handle a mouseClick, since an ActionEvent is guaranteed to be generated, whereas as mouseClicked event when using a MouseListener may not be generated in all situations, which can confuse the user.

Upvotes: 13

Erick Robertson
Erick Robertson

Reputation: 33078

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.

Upvotes: 34

Related Questions