JLabel的ActionListener有图片初始化

时间:2013-03-28 18:33:35

标签: java swing actionlistener jlabel

如何为JLabel制作actionListener?我想如果我们双击这张图片(即在JLabel上),它会调用一些函数..

我认为Jlabel的actionListener是不同的,因为它给出错误

1 个答案:

答案 0 :(得分:3)

以下是关于如何完成此任务的简短演示。

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();
            }
        });
    }
}