如何为JLabel制作actionListener?我想如果我们双击这张图片(即在JLabel上),它会调用一些函数..
我认为Jlabel的actionListener是不同的,因为它给出错误
答案 0 :(得分:3)
以下是关于如何完成此任务的简短演示。
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();
}
});
}
}