Asdakamessoy
Asdakamessoy

Reputation: 87

ActionListener for JLabel having picture init

how to make actionListener for a JLabel ?? i want like if we double click this picture(that is on a JLabel) it will call some function..

actionListener for Jlabel i guess is different because its giving error

Upvotes: 0

Views: 3073

Answers (1)

Vishal K
Vishal K

Reputation: 13066

Here is the short Demo of how you can achieve this task..

enter image description here

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class MouseClickOnJLabel extends JFrame 
{
    public void createAndShowGUI()
    {
        JLabel label = new JLabel("Double Click on me!!");
        getContentPane().setLayout(new FlowLayout());
        getContentPane().add(label);
        label.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent evt)
            {
                int count = evt.getClickCount();
                if (count == 2)
                {
                    JOptionPane.showMessageDialog(MouseClickOnJLabel.this,"You double clicked on JLabel","Information",JOptionPane.INFORMATION_MESSAGE);
                }
            }
        });
        setSize(300,200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }
    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater( new Runnable()
        {
            public void run()
            {
                MouseClickOnJLabel moj = new MouseClickOnJLabel();
                moj.createAndShowGUI();
            }
        });
    }
}

Upvotes: 3

Related Questions