Add mouse listener to a custom JLabel in Java
Description
The following code shows how to add mouse listener to a custom JLabel.
Example
//ww w.ja v a 2 s. c o m
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JLabel;
import java.awt.GridLayout;
import javax.swing.JFrame;
import javax.swing.plaf.basic.BasicArrowButton;
public class Main {
public static void main(String args[]) {
JFrame frame = new JFrame("Popup JComboBox");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MyLabel("java2s.com"));
frame.setSize(300, 200);
frame.setVisible(true);
}
}
class MyLabel extends JLabel {
public MyLabel(String msg) {
super(msg);
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
fireActionPerformed(new ActionEvent(MyLabel.this, ActionEvent.ACTION_PERFORMED,
"SecretMessage"));
}
});
}
public void addActionListener(ActionListener l) {
listenerList.add(ActionListener.class, l);
}
public void removeActionListener(ActionListener l) {
listenerList.remove(ActionListener.class, l);
}
protected void fireActionPerformed(ActionEvent ae) {
Object[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++) {
((ActionListener) listeners[i]).actionPerformed(ae);
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »