Java Swing How to - Extend JLabel to handle action event








Question

We would like to know how to extend JLabel to handle action event.

Answer

//from ww  w  . ja va2s. co  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 javax.swing.JOptionPane;

public class Main {
  public static void main(String[] args) {
    MyLabel label = new MyLabel("java2s.com");

    label.addActionListener(e->{
      System.out.println("hi");
    });
    
    JOptionPane.showMessageDialog(null, label);
    
  }
}
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);
    }
  }
}